The code in (Your second "for" loop) is wrong


#1



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


wrong code but it let me pass the exercise. I wrote the right code but it kept telling me there was something wrong.


/*jshint multistr:true */

var text = " Hi every one My name is Leo and I'm leaving the US with a big success, I always love Leo becaue it's my Geos name" 

var myName = "Leo"

var hits = []

for ( var i = 0 ; i < text.length ; i++){
    if (text[i] === "L"){
        for ( var j = i ; (j < myName.length + i) ; j++){
            hits.push(text)
            }
        }
    
    
    else if ( hits[0] =='' ){
        console.log("Your name wasn't found!")
        }
        console.log(hits[i])
}


#2

Hey @megablaster68696,

you have a few, some major, some less major, mistakes in your code - I listed them below for you.


  1. SEMICOLONS!!! ; - do you know what they are made for? You forgot it like everywhere .. How did the compiler let your code pass even through the first line, lol.
  2. Close your outer (the first) for-loop after your if-statement.
  3. You have to push the text on your current index-position, which means -> hits.push(text[j]);
  4. Remove the else infront of your second if - it's not neccessary, cause this should be a single if-statement.
  5. The condition for this if-statement is wrong aswell. You currently check, if hits is empty ('') at the first position ([0]) -> replace it with a check if the .length of hits equals zero (0).
  6. To many ifs belongs an else, such as in this case. Which means you need also an else-statement which loops through your hits and logs them to the console. Therefore you need a new for-loop.

All in one, your code should look something like this:

/*jshint multistr:true */

/* I'm using backslashes here to "break" your sentence down */
var text = " Hi every one My name is \
Leo and I'm leaving the US with a big \
success, I always love Leo becaue \
it's my Geos name"; 

var myName = "Leo";

var hits = [];

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

if(hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    for(var x = 0; x < hits.length; x++) {
        console.log(hits[x]);
    }
}

Hope this will help you :slight_smile:


#3

Thank you for pointing out my mistakes. The issue is when I wrote the correct code the website wouldn't let me pass but when I wrote it in this style( many mistakes ) it let me pass


#4

Well, that shouldn't be.. But happens sometimes (Cache-bug)


#5

I just finished this part with the help of the responses on this post! Not really sure why but I was able to get past a lot of the tasks without adding semicolons until I reached this task. Strange, but it work! Thanks!