5. your second for loop



var text = "hi im jon. your not jon, im jon.";
var myName = "jon"
var hits = [];
for (var i = 0; i >= text.length; i++) { 
if(text[i] === 'j')   
 { for(var j =i; j < i + myName.length; j++){
     }   }


the problem is in the first loop:

for (var i = 0; i >= text.length; i++)

this condition evaluates to false in the first run, so will never run. Maybe you need to change the condition so it can loop over the string stored in text?


thanks stetim94 for you quick reply and your help but it hasnt made a difference. I changed the code. Plus i dont even understand the question where all of a sudden did j come from in the for loop?

var text = "hi im jon. your not jon, im jon.";
var myName = "jon"
var hits = [];
for (var i = 0; i >= text.length; i++) {
if(text[i] === 'j')

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

 }   }


no, the code i posted is just to mark where the problem is, i gave you a push in the right direction, you still have to figure out why the loop is wrong. I am here to help you learn, not just to provide you with the solution, take a second to think over why the first loop is flawed, if you need more help let me know, i will of course help you further

uhm... you declare j in the loop? just you declare i in the first for loop, except you don't assign a fixed number to it, but rather a number stored in a variable (j = i, give j the value of i)


Got it cheers. I know you guys aren't here to give me the answer, i just thought you did. Thank you for your help :). I kind of understand the j part but still not 100% sure why it appeared and with no explanation. maybe im over complicating it :confused:


good to hear you got it solved :slight_smile:
i wrote some extensive explanations about the second for loop in this topics:

The problem with such explanations is that they are time consuming to write, i hope they help you


what first 'for' loop does is loop from 0 to text length. Lets assume it is 25. Now, for the most part, the loop will not run further because the if statement is not true. text[0] = h, text[1]=i, text[4]=m. Now, once text[i]=j, that's when if statement executes. In your example, text[6]=j (string count starts at 0 and spaces are counted)

Now, why used j ?
Because we want to create a new loop that starts with 6th position, our 'j' is located at 6th position in your text. So, we made j=i. Now j=6.
Now, 'for' statement starts at 6 and loop till <6+myName.length i.e <6+3 i.e 8
Then we just push the letters at 6th 7th 8th position to array by using .push
It gets text[6] = j, text[7] = o, text[8] = n

Hope that clears your confusion. :slight_smile:


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