Now this interview question is very popular:

for (var i = 0; i < 10; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

The result of this code is ten times repeated 10. The value of i in each function callback is window.i, because var creates global variable. This moment is not obvious on my opinion: for(var i… is is nothing different than var i. So, how to save value of i on each iteration… There is a few methods:

1)

for (let i = 0; i < 10; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

Let was introduced in ES6. This keyword creates block-scoped variable. Meaning that it is visible in { } braces only, setTimeout evaluates in the created scope and outputs saved i value.

2)

for (var i = 0; i < 10; i++) {
  setTimeout(
    (function(r) {
      return function() {
        console.log(r);
      }}
    )(i)
  , 1000);
}

Here we created lexical environment using a self executing function and i current value is saved in local variable r, which is available via closure.

Leave a Reply

Your email address will not be published. Required fields are marked *