Quiz on asynchronus question 2

why the answer is not 012345 as when it moves into setTimeout it comes out of it after i*1000 millisecond and the again for loop run.

Send the entire code along with your query.

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

The answer would be 012345 if you used “let” instead of “var” in the for loop.
This is because “var” is function scoped, meaning that it once var is initialised, the same memory will be used across all the iterations of that loop, while “let” is block scoped, so for each iteration of the loop, a different memory is used.

A little more detailed answer here: https://stackoverflow.com/questions/31285911/why-let-and-var-bindings-behave-differently-using-settimeout-function

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.