Loops and Arrays II - 12/13


#1

Hello,
Is something wrong in here?

// Click on "Stuck? Get a hint!" if you get stuck!
var names = ["Geralt", "Yennefer", "Cirilla", "Triss", "Gerund"];

for (var i = 0; i < names.length; i++); {
console.log("I know someone called " + names[i]);
}

Edited - ah yes the mistake here is in "for (var i = 0; i < names.length; i++);" where it shoudn't be semi-colon at the end.


#2

The Javascript interpreter,
interpretes a semi-colon-;
as an End-of-Statement indicator.


#3

The longer explanation first needs to start with the fact that the {} after loops and conditions being mandatory is only partially true. In fact you don't need them if and only if there is just one statement following. This behaviour is not covered in the track and you're recommended to use them anyway because they increase readability if the code is well formatted and because for more then one statement they are mandatory.

That's just to introduce the reason why it is not throwing an error although you have a semicolon instead of {}. Now the problem is as @leon explained that a semicolon is an End-of-Statement indicator which leads to fact that a lonesome semicolon is a statement of it's own. Probably the most useless of all statements as it does literally nothing, as it is ended before it even begins, but it's a statement.

Which leaves your for loop to be this:

for (var i = 0; i < names.length; i++);

Which does absolutely nothing but counting up i. And your intended loop body:

{
    console.log("I know someone called " + names[i]);
}

becomes regular code as it is not connected to the loop. Now when your loop has finished doing nothing i has a value of names.length. Although the loop body is pointless you still increase after each loop. Now when you run your intented loop body you receives "I know someone called undefined" because names[names.length] is for obvious reasons undefined (out of boundaries).

Hope this makes the error a little clearer and shows how important it could be to watch for semicolons. Because in the end the most crucial mistakes are those that do not throw an error but do unintended stuff because it takes a lot longer to find them :stuck_out_tongue_winking_eye:


#4

Thank u :heart_eyes: :blush: