The answer would be Option 2: 55555 because

  1. var i in the loop will be defined in outer scope which is equal to
var i;
for (i = 0; i < 5; i++) { ... }
  1. Loop will run from 0 to 4 but will break when i will be 5.
  2. setTimeout will schedule 5 callbacks which will run after at least 10 secs.
  3. Since, i is defined in the outer scope, its value will be overwritten on each iteration and final value will be 5.
  4. When callbacks are executed, they will get the final value of i i.e. 5.

To capture each value of i in the respective callbacks, there are two popular solutions to the question.

  1. Changing var to let which we redeclare i on every iteration.
for (let i = 0; i < 5; i++) {
	setTimeout(function() {
		console.log(i);
	}, 10);
}
  1. Returning an inner function and using closures.
for (var i = 0; i < 5; i++) {
	setTimeout(function(i) {
		return function() { console.log(i); }
	}(i), 10);
}

For useful and amazing frontend and programming tutorials: https://bit.ly/devtools-yt

Recommended Resources