Search Text For Your Name Javascript Help


#1

Hello, my code is working, but I'm having trouble grasping the concept of line 9. Could someone explain what's going on?


#2

Someone may have a more formal explanation, but as someone who's also learning to code, when I don't understand something, I pretend I'm back in either algebra or calculus class, and just plug in the numbers and run them through the code I'm trying to understand.

From that approach, let's look at the section at hand. The code is meant to find your name by comparing characters in the string. So, the first character it would find, is A, but at what index?

If we count the letters, starting with zero at H, all the way to A in the first Allen, we find that the index is 18.

Knowing that, let's look at both line 8, 9, and 10:

// if A  === A,
    if(text[18] === myName[0]){
      //myName.length is equal to 5
      for(var j = 18; j < (18 + myName.length); j++){
        //add the character A found in variable text to the empty array "hits".
        hits.push(text[18]);
      }
    }

Since we are inside loop with index j, it will iterate all the way through 18 + myName.length, or until j < 23 is true, which is between when it finds the first letter of the name and when the name ends. So what happens when the incrementation j++ occurs, and j is now equal to 19?

for(var j = 19; j < (18 + myName.length); j++){
     //add the character l found in variable text to the array "hits".
    hits.push(text[19]);
}

and when j = 20?

for(var j = 20; j < (18 + myName.length); j++){
     //add the character l found in variable text to the array "hits".
    hits.push(text[20]);
}

and 21?

for(var j = 21; j < (18 + myName.length); j++){
     //add the character e found in variable text to the array "hits".
    hits.push(text[21]);
}

So far, this is what hits looks like:

hits[0] = A
hits[1] = l
hits[2] = l
hits[3] = e

Do you see what's happening?


#3

Great explanation, I totally get it now. Thanks for your help! @myssandria