Javascript, what's wrong with this for loop syntax?
Can anyone help me?
I am currently learning Javascript and I do not understand what happened to the following piece of code:
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < 4; i++); {
console.log("I know someone called " + names[i] + ".");
}
because you end the for loop with a semicolon (;), so the for loop is separated by its block.
then
Ques1. What happens next when the code runs?
Ans. when execution is done for a loop, the loop executes until i reaches 4 . then the next block statement is executed.
Ques2. Why is "manuel" printed in o / p?
AnswerAns. simple because the loop closes when the value i go to 4 , so
console.log("I know someone called " + names[i] + "."); //it prints the arr[4]
You have; at the end of yours, just remove it
JavaScript arrays are zero-indexed. This means that the element at the very first position is in the index 0
. To target this item, you can link to it as names[0]
. In your loop, you are iterating i < 4
, meaning that once i
becomes 4, the loop stops and does not continue. This way you console.log
only call 4 times. A common practice when iterating through an array is to say i < names.length
. There are also a couple of syntax errors as others have pointed out. Below is a working version.
for (var i=0; i < names.length; i++) {
console.log ("I know someone called"+" "+names[i]+".");
}
Please remove the semicolon after:
var names=["vasco","joão","francisco","rita","manuel"];
for ( var i=0; i <5 ; i ++) {
console.log ("I know someone called"+" "+names[i]+".");
}
also the condition i <4 is the stop of the last case
there are two questions with the code you wrote,
1- you have a semicolon after the condition for(condition);
causing the loop to do nothing
2- you are off by one, the last element of the array has a 4
condition index must be (i <= 4)
or(i < array.length)
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < names.length; i++){
console.log("I know someone called " + names[i] + ".");
}