# Why "+i" to myName.length in Second Loop?

#1

My code works and I could finally finish this section only after I read this forum. I studied the other answered-question for "Your second 'for' loop explanation" [from stetim94] and it helped... Only one last element that I still don't understand - If the second loop is to start the count again, should it merely be "j < myName.length" ? What is the "+i" about right behind that?

I tried taking out the "+i" and it doesn't work, but have no idea why we need it. Please explain? Thank you so much.

``````/*jshint multistr:true */
var text = "Hey, how are you \
doing? My name is Emily.";
var myName = "Emily";
var hits = [];

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

if (hits.length === 0) {
} else {
console.log(hits);
}``````

#2

so the goal of our program is to find all instances of `myName` in `text`

so our first loop, loops over `text` looking for the first letter of your name (`E` of Emily)

which is found at index 35 in text. so then `i` is 35 (thanks to if condition), now our second for loop needs to loop from index 35 till 40 (exclusive). We can do this by using `< i + myName.length`

because `i` may vary (given where and how many times your name is present in `text`) we can use `i` (index of first letter of your name in text) + myName.length, which will contain the index after our name, to extract our name from text string

#3

Awesome! This whole section finally makes sense now! Thanks!

#4

But if j = i doesnt "j < (myName.length + i)" also mean the same thing as "j < (myName.length + j)"? Or is it that j = i but "i" does not equal "j"

#5

no, because you will increase `j` (`j++`), so then you get an infinity loop

`i` will remain the same while you use the second for loop to push the letters of your name into an array

#6

Hi, I have a quick question about this. Wouldn't i + myName.length (in this example) be 35 +5? Which would mean that the loop will iterate 40 times? I'm little confused.

#7

because that is only part of the condition, if we look at the condition:

``j < (myName.length + i)``

and then fill in the numbers:

``35 < (35 + 5)``

you will see it only finds the letters of the name.

#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.