Why is 3 printed in the end of the loop?


#1

wrote a code for this lesson:

// Write your code below!
for (var i=0; i<=3; i++){
console.log ("For loop") ;
}

i = 0;
while (i<=4){
console.log ("While loop");
i++;
}

i = 0;
do{
console.log ("Do/while loop");
i++;
} while (i < 4);

Evrth workes fine, but in the end of console output the 3 digit is logging. Where does it come from? what is the source of this logging?


#2

In Javascript, all statements (including for loops) have a value which is returned when the statement has concluded. undefined is returned if no operations take place in the statement, so nothing would be printed to the console in this case. You can check this out for yourself if you rearrange your code and place the first for loop at the end of your code.

Since i is the last (and only) operative value used within the second two statements, it logs the last value of i to the console.

This is normal behaviour and nothing to worry about - the interpreter simply prints the return value to the console for you for debugging purposes.