Can anyone explain why the following code works when run as part of function, but it produce strange result when run by itself in the Chrome Console window?
var foo = function() {
var x = 1;
while (x<3) {
console.log(x);
x = x+1;
}
}
foo(); // This prints 1,2 as expected
But when I run just while
part directly in Chrome Console I get 1,2,3 which makes no sense (see image for the output):
var y = 1;
while (y<3) {
console.log(y);
y = y+1;
}
// This prints 1,2,3 in the console
Note that there somewhat similar question about console.log
resulting in undefined
(Chrome/Firefox console.log always appends a line saying undefined), but there is no function call in my sample and while
does not ever return any value.
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.
It isn't just restricted to the console, as shown via:
<script>
console.log(eval("var y = 1;while (y<3) { console.log(y);y = y+1;}"))
</script>
That is a rough way to go about replicating the output, but it may be noted that eval
will preform in the same way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With