Var J = i - Why the need to change variables?


Hi, I'm just having a tough time understanding this part of the code: (var j = i). It mentions how var j continues where var i left off but why don't we just use var i instead? I tried it and it keeps crashing my browser haha, so obviously it doesn't work. I'm just curious why.

Replace this line with your code.


/*jshint multistr:true */

var text = "Hey, how are you \
doing? My name is Ygames. okokkokokokoko Ygames";

var myName = "Ygames";

var hits = [];

for (var i = 0; i < text.length; i++){
    if(text[i] === myName.substring(0,1)){
        for(var j = i; j < i + myName.length; j++){

This worked for me. If the i sees youre first letter then he will say to j start from i count from that to youre names length. So in my example it will ygames.length so i will say to j to start and pushing at y and stop after 6 and push that into youre hits val


Okay, thanks! I think I understand it, so j var is literally carrying forward from the var i.

If possible, could you explain why we need: i + myName.length? I know it won't work without it but I don't understand why that is. What's the purpose of var i in that instance?


It goes until i + length.myName is smaller (<) then j
the outcome of length.myName is a number btw so j < i + 6 in my example


we use the second for loop to loop over our name in text, thanks to your if statement, i contains the index of the first letter of your name.

But we also need to stop our loop once it reaches the end of our name in text, but how? For this we use i + myName.length, given i is the start index, our name has a length which we use here, to find the last index.


Okay, this really helps me understand it. Thank you.

My last question is: maybe it's super obvious but why does do these print out different numbers: console.log([i])

They're ending a few digits separately from another. Why is this?


this depends where you put this console.log statements, can i see full code?


Thank you for willing to take a look at this, don't mind my silly strings. :slight_smile:

var text = "Chris is happy to see you\
            Chris is very happy.\
            Chris loves you.";
var myName = "Chris";
var hits = [];

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


i will stay "fixed" while you use the second for loop to loop over your name, that is why they are different


Thank you! So the second for loop is just looping over my name again and again, right? And then it stops because of j < (myName.length + i)?


yea, given each iteration of your second for loop gives one letter, you will need to loop multiply times to find all letters


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