JavaScript while loop in console prints additional results

Can someone explain why the following code runs when run as part of a function, but it gives a 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 only the while part directly in the Chrome console, I get 1,2,3, which makes no sense (see image for output):

  var y = 1; while (y<3) { console.log(y); y = y+1; } // This prints 1,2,3 in the console 

enter image description here

Note that there is a somewhat similar question about console.log leading to undefined ( Chrome / Firefox console.log always adds a line indicating undefined ), but in my example there is no function call, while while never returns any value.

+6
source share
2 answers

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() .

+10
source

It is not limited to the console, as shown through:

 <script> console.log(eval("var y = 1;while (y<3) { console.log(y);y = y+1;}")) </script> 

This is a crude way to replicate output, but you will notice that eval will be stub in the same way.

+1
source

Source: https://habr.com/ru/post/946136/


All Articles