6.5 -- What's wrong with this code?


#1

When I run this, I get the error "Oops, try again. It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable."

I've changed it so many times, and no matter what I change I can't get it to work. I'm sure the error is simple and embarrassing, but any help would be very appreciated!

var text = "From Stallman's perspective, the emotional withdrawal was merely an attempt to deal with the agony of adolescence. Labeling his Sam teenage years a 'pure horror,' Stallman says he often felt like a deaf person amid a crowd of chattering music listeners."

var myName = 'Sam';

var hits = [];

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

#2

Your loop bodies are entirely empty

// this is your loop
for ( var i = 0; i <= text.length; i++);


// this comes after the loop
{
    if (text[i] === 'S') {

        // and again, this single line is a loop with an empty body
        for (var j = i; j < (i + myName.length); j++);


        // and this comes after the loop, it's not the body of the loop
        {
            hits.push(myName)
        }
            
    }
}

Another example:

for (var i = 0; i < 10; i++);
{
    console.log("this is only printed once, because it's not in a loop");
}

#3

I'm still lost... Isn't my first loop body checking 'S' against each letter? And the second one pushing that letter into 'hits' ? Could you provide an example of what a proper body might look like (just a generic form would be really helpful).


#4

The loop body is a single statement.

{}'s can be used to group multiple statements into one statement.

You've instead put an empty statement, and then you've got some {}'s with code in them but they're not part of the loop because only one statement is included and you've already got that.

A semi-colon ends a statement. If you place a semi-colon where there isn't a statement, then you've got yourself an empty statement.

If you're not sure where semi-colons go, then look up the thing you're writing to see whether it ends in semi-colon or not.


#5

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