Your second "for" loop


#1

<I have been stuck on this for hours!! I Don’t know what I’m doing wrong.>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661#

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
Oops, try again. Careful: your second ‘for’ loop should stop when it reaches its current point in the string + myName.length.

```

/*jshint multistr:true */

var text = “hi”;
var myName = “Jas”;
var hits = [];

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

<do not remove the three backticks above>

#2

Hi @jas_0131,

var text = “hi”;

try make the string in text longer and insert your name Jas at least once (so that you can see your name being printed in the console, if not it will not print anything since your name Jas is not in the text)

your second ‘for’ loop should stop when it reaches its current point in the string + myName.length.

so it should be

for (j = 0; j < (myName.length + i ); j++){

Brief explanation: Let’ say when your first loop start going from 0, 1, 2, 3, 4, and when i = 5, at text[5] you found your ‘J’, you would want your second loop to start looping at j=0, iterate until myName.length + i (“Jas”.length + 5, means 8, so the second loop will stop at text[8]). If you need more explanation, there are more detailed ones in the forum.

lastly, it should be

hits.push(text[j]);

instead of

result.push(text[j]);

where does the result.push come from?

Hope it helps :slight_smile:


#3

This task is just way too hard. All that nesting makes it so hard to grasp. I can’t be the only one, right?


#4

it is difficult to understand because of the nesting and all of the different variables involved. however, if you break it down into pieces it shouldnt be that bad. stuff like this is why i normally prefer to do a longer method of coding. i dont mind the extra typing if i can understand it when im done. most of my job requires me to go back behind 2 other developers to find weaknesses and/or errors in their code. its one thing if you cant understand your own code, given that you at least should know what its supposed to do. but going behind other people when you have no idea what they were trying to accomplish or what was in their head at the time is grueling. so i would much rather write everything out so that its plan rather than trying to squeeze everything into one or two functions/loops.


#5

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