UP | HOME

Explaining var and for loop problem

One of the usually example given to convince people start using let instead of var is:

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

With the above code, the output is, all 5, instead of a sequence from 0 to 4:

5
5
5
5
5

Why does that happen? Why using let solves the problem? Is let the only solution? Let's dive into this.

Date: 2019-01-17 Thu 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41