AbhimanyuSingh AbhimanyuSingh - 1 year ago 46
Javascript Question

setTimeout in for-loop prints unexpected garbage value for the first time when run in console window

for (let i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );

The above works in this snippet, but when ran in the console window I get unexpected results. The first value is garbage. What is the reason behind the first garbage value that gets printed?

enter image description here

Answer Source

Value being printed in console is returned value of setTimeout([timeoutID])

As you are executing your code in console, first value is always returned value of expression

In your case, for loop is being iterated 5 times, returned value is always incremented by 5 hence values will be 5..10..15 and so on. Latest value of setTimeout is returned.

One must have observed undefined being printed while executing code in DevTools Console, it is because of executing void-function, if expression returns a value, it is printed.