I did it but I don't know quite get what's going on in second loop


#1
var text = "test Julian Julian Julian";

var myName = "Julian";

var hits = [];

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


if (hits.length === 0) {
    console.log("Your name is not found")
    } else {
        console.log(hits);
    }

This is what I wrote and it works perfectly but I don't quite understand.

    for (var j = i; j < (myName.length + i); j++) {
        hits.push(text[j])

In this second loop, I see var j = i j is declared as i but I don't understand what myName.length + i is doing. I know it's the stopping point. And I get the push thing but what is it doing?


#2

Hi,

myName.length gives you the length of your name (from Julian it is 6)
If your second loop runs you know the position of your first searchletter (J) it is stored in var i.

Try a console.log(i); before your for loop and you will see the position.
In your example it is in 5, 12, 19.

So you know your name is six letters long and the first letter begins on position 5
You have now the times how often the for loop must run. var j is 5 the for runs so long until j is bigger than myName.length + i (11)
var hits is an array and with push we can add values.

//first round in your loop 
hits.push(text[j]);  //text position 5 is the letter J

// second round in your loop
hits.push(text[j]); // text position 6 is the letter u

// third round in your loop
hits.push(text[j]); // text position 67 is the letter l

// and so on until your condition hits