Why is there a + i in exercise 5?


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++) {

There is not a problem with this code( model code). But I am clueless to starting exercise 5. What is the function of
+i in for(var j = i; j < (myName.length + i); j++) {

Replace this line with your code.


And also another question: why is j=i?


The i represents a changing index, it indicates the numerical position of something in your array or string etc, and counts up from 0 onwards.

The first loop (index called i) searches through all the text characters for any words beginning with "E". When it spots one, the second loop (index called j) then searches that particular word's characters to see if it matches the length of the name "Eric".


Thank you. That really clear up some confusion.
But I'm still not understanding why it is
j < (myName.length + i)
instead of
j < myName.length


For example, if your text says "blah Eric blah", the first occurrence of "E" is found at i-index position 6. You have to add to the current index position of 6 (+ i) to count the rest of the letters, simply because they will be passed at position 7, 8, and 9.

j < (myName.length + i)

This logic means you are asking the loop to stop before it hits (myName.length + i), which is 4 + 6 = position 10. So the loop will stop at position 9, just after the "c", which is what you want.


Thank you. I had the same question. The counting is tricky because we have to count from 0.


This tied my brain in a knot - I had to draw it out to make any sense of it.

I hope this is helpful!

Say 'i' is at position 10.
The second loop begins.
You then set 'i' to 'letter'. Now 'letter' equals 10.

In the second loop, the value of 'i' remains 10 until the conditions of the second loop have been met, i.e., 'letter' is less than the myName.length.

So let's break down the second 'for' loop:

for(var letter = i; (letter < myName.length + i); letter++) {
1st: (10) (10) < 4 (Eric) + 10) (11 -> we will use this in second loop) ('E')
2nd: (10) (11) < 4 + 10) (12 -> we will use this in third loop) ('R')
3rd: (10) (12) < 4 + 10) (13 -> we will use this in fourth loop) ('I')
4th: (10) (13) < 4 + 10) (14 -> will not use again, 13 < 14, loop can't go further ('C')

And it's done! I hope that was an OK visualization and line breaks don't make my formatting look all screwy.