Kenneth .J Kenneth .J - 8 days ago 7
Javascript Question

Use of string.length + counter variable

I'm new to programming and am currently learning javascript on CodeAcademy. This code below is from a tutorial where the program will search a string to look for a name. The program will loop through the array, compare each letter to the first letter of your name, and if it sees that letter:
It will push that letter and all the letters that follow it to an array, stopping when the number of letters it pushes are equal to the number of letters in your name.

What I don't understand is the line :

for (var j = i; j < (myName.length + i); j++)

why does
j <(myName.length + i)
and not
j<(myName.length)
? If the letter "E" of "Eric" is the 25th character in the string, wouldn't
j<(myName.length + i) = j<("4" + "25")
which is wrong as it the correct code should be
j<("4")
where 4 is the length of the name Eric.

I've tried running the code with
j<(myName.length)
but it fails to work and I cant seem to understand why.

text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] == "E") {
// If we find it, add characters up to the length of my name to the array
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

Answer

In your inner loop, you are doing this:

for(var j = i;

When condition if (text[i] == "E") { gets satisfied, the value of i is very high (30).

Now, when you do this:

for(var j = i; j < (myName.length); j++) {

you are basically doing this -

 for(var j = 30; j < 4; j++) {

So the loop never starts; as the boundary condition is not satisfied.

But when you do this:

for(var j = i; j < (myName.length+i); j++) {

then you are doing this:

for(var j = 30; j < (30+4) ; j++) {

Hence everything works, the way it should.

Comments