Lesson 5: Your second for loop. Help


So I put this into the system, and I got it right.

But honestly, I don't really know what I did. I just kind of saw what others were doing on the forums and tried it.
Basically... can someone translate my code to English, so I can understand what I'm telling the computer to do?

Exercise: https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/5?curriculum_id=506324b3a7dffd00020bf661

/*jshint multistr:true */
var text = "Hello, my name is Clover."
var myName = "Clover"
var hits =[]

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


Should help:


So... what exactly is j? What does the computer understand it to mean?


I'm still puzzling this out but I'll attempt to explain it because it is beneficial to me too. J is just a variable. the letter does not matter. it could be 'x' or 'c' or 't'. In this program the j variable is equal to the 'i' value in the first for loop. Remember, we are working with a for loop within a for loop. The first loop scans the text until it finds the letter you tell it to find using this part of the code : if (text[i] === "C"). in your code, the letter "C' is on the 18th line of the string, or index[18]. so now for your code, i = 18. So the next for loop looks like this.

Here we first set our variable 'j' to the variable 'i'. They both equal 18 now. At the end of our for loop we have j++ because we want the for loop to increment by one every time. So 18 then 19, 20, 21, and so on. But we want the for loop to stop when it reaches the length of your name. that's where j < i + myName.length comes in. so when j < (18) + 6 the code will stop.

Hope that helped somewhat.


And your second for loop should be:

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


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