You are being misled by Chrome's JavaScript console.
In addition to the output of console.log() calls, the console also displays the value of the last expression executed in the code you run there.
In your first example, the last expression is the foo(); call at the end. foo() doesn't return any value, so the result is undefined and that's what's printed after the 1 and 2 that your console.log(y) calls print.
In the second example, console.log() is still being called only twice, again printing 1 and 2. The 3 printed after that is not from a console.log() call, it's the value of the last expression executed, the final y = y + 1; that brings y up to 3 and causes the while loop to terminate.
Here's 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"
The 1 and 2 are again from the console.log(y) calls as before. Like the other examples, after the code finishes running it prints the last expression executed—but now that expression is:
message = 'y is ' + y;
where y is again 3 at the end.
Or a much simpler example. Enter this in the console:
console.log( 'Hi!' );
It prints:
Hi!
undefined
The Hi! is your console.log() executing, and the undefined is the return value of the console.log() call.
Another clue here is the little symbol to the left of the last value printed to the console in each of the examples. It looks like that symbol means that the dev tools are printing the value automatically instead of from a console.log() call.