Search for your name in text -- please explain logic in 2nd for loop


#1

I have this piece of code:

for (var i = 0; i < text.length; i++) {
if (text[i] === "L") {
for (var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

I understand the first for loop and what it's doing and the if statement as well but can someone please explain the logic for the 2nd for loop and what it's accomplishing? The thing that is throwing me off is why are we setting the end point of the loop as j < (myName.length + i)? I get the rest of the code and im sure it's something minor but i dont wanna move on if i don't fully understand the logic


#2

What your second for loop is doing:

1st:

Using the first for loop, the code quickly scans the text for "L".

2nd:

Using the second for loop, the code finds the entire word of myName, and follows each letter to see if there is the word of myName in the text.

3rd:

hits.push(text[j]);

Is a way to put that word that the code had found in the text into the hits array.

4th:

You might have done this, but doing console.log(hits) at the end will print out the word of myName that was found in the text.

Hope it helped!:smiley:


#3

thanks, i got everything you pointed out i just wasnt sure why we set the 2nd for loop to j < (myName.length +i) but i think i got it now.

we are basically just adding the length of the myName variable to i (where the loop first detects the first letter of my name) to get all the letters of my name. Dont know why i didnt think of that in the first place. Thanks again!