-3

Running the following code in the console:

for (var i = 0; i < 5; i++) {
    let j = i;
    setTimeout(function(){
        console.log(j);
    }, 0)
}

results in some strange behavior. When I run it once, I see something like:

enter image description here

What is that number at the top?

9 // what is this????
0
1
2
3
4

The next time I run it, it's different:

13 // what is this????
0
1
2
3
4
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Potter
  • 3
  • 2
  • That's the return value of `setTimeout()`. In browsers, the handle is a positive integer that can be passed to `clearTimeout()` before the callback is scheduled to execute if you want to cancel it. – Patrick Roberts Feb 18 '20 at 07:50
  • Its return value of `setTimeout` function to be stored and used in case `clearTimeout` is needed. – Umair Khan Feb 18 '20 at 07:53
  • Thanks, I first thought it's returning some stack size. – Potter Feb 18 '20 at 07:58
  • Relevant part from the spec (wrt duplicate): https://www.ecma-international.org/ecma-262/10.0/#sec-for-statement-runtime-semantics-labelledevaluation – Felix Kling Feb 18 '20 at 08:20

1 Answers1

1

The console will log the result of the final expression that was evaluated. This is why, for example, typing in

'foo' + 'bar'

results in 'foobar' being logged.

Here, the final expression evaluated (synchronously) is the setTimeout, and setTimeout returns an integer indicating the ID of the timeout (which can be used with clearTimeout later). setInterval works the same way. So the number you're seeing is that timeout ID. (it sounds like setTimeout was called 12 times previously on that load of the page)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • It's not "just" the final expression (if that was the case, `var foo = 1` would log `1`), it's the "result" of the `for` loop. – Felix Kling Feb 18 '20 at 08:18