-1

I was just messing with some stuff when I stumbled on this. I have the following code:

for(var i = 0; i < 5; i++){
  let x = 10;
  console.log(x);
  x = x + 1;
}

Well, this seems pretty simple: A for loop, which will print the content of x (10) 5 times. But the weird think is, when i ran this on my browser (Chrome, on the last version) the actual result was 5 logs of 10, and 1 log of 11.

Thinking there was a bug on chrome, i tried to run this on repl.it (a website to run code in some programming languages online), the result was the same.

So i tried to run this os some different browsers as well, so after a ran this on Edge and Brave, i still got the same result.

But when i run this on node.js i get the expect result, which is 5 logs of the value 10.

So my question is, why this is happening on all browsers and only node is logging the right result ?

Additional information:

  1. This seems pretty weird to me, since both chrome and node.js use the same javascript engine (V8).
  2. I know Brave has the same engine, since it's based on chromium but I tested it anyway, since the same engine is shared between chrome and node, and the result was different.
  3. The node version i'm currently using is: v12.18.3
  • It is very strange. Do you `console.log` any other data or the loop is the only thing in your code? –  Nov 08 '20 at 19:15
  • 1
    Does this answer your question? [JavaScript while loop in console prints extra results](https://stackoverflow.com/questions/16826584/javascript-while-loop-in-console-prints-extra-results) – Ivar Nov 08 '20 at 19:21

1 Answers1

5

The "11" you see is not actually a log, but the return value. Chrome, and many other browsers, make a for loop implicitly return the result of the last expression for convenience when debugging. image

That's why, unlike the logs of 10, it has a left arrow to the left of it.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • I was so dazed because of the unusual behavior that i didn't see the arrow returning the value. Thanks for the explanation, i didn't know that by default there was an implicit return. – Rafael Zeferino Rossi Nov 08 '20 at 19:46