The Chrome JavaScript console is misleading.
In addition to outputting console.log() calls, the console also displays the value of the last expression executed in the code that you ran there.
In your first example, the last expression is a call to foo(); in the end. foo() does not return any value, so the result is undefined and what prints after 1 and 2 , which your console.log(y) calls are console.log(y) .
In the second example, console.log() is still only called twice, again printing 1 and 2 . 3 , printed after this not from calling console.log() , this is the value of the last executed expression, final y = y + 1; , which brings y to 3 and causes the completion of the while .
Here is another example. Paste this code into the console:
var y = 1, message = ''; while( y < 3 ) { console.log( y ); y = y + 1; message = 'y is ' + y; }
Now it prints:
1 2 "y is 3"
1 and 2 reappear from console.log(y) calls, as before. As in other examples, after the code completes, it returns the last expression executed - but now this expression:
message = 'y is ' + y;
where y again 3 at the end.
Or a simpler example. Enter this in the console:
console.log( 'Hi!' );
He prints:
Hi! undefined
Hi! is your console.log() execution, and undefined is the return value of the console.log() call.
Another clue here is the small character to the left of the last value printed on the console in each of the examples. This symbol seems to mean that dev tools print the value automatically instead of calling console.log() .