0

There is something I didn't really understand clearly, If somebody could help me:

let arr = [1,2,3,4,5,6,7];

let b = 0
for (let a of arr) {
    setTimeout(() => {
        console.log(b, a)
    }, 2000)
    b = b + 1;
}
/* Output 
7 1
7 2
7 3
7 4
7 5
7 6
7 7
*/

Let's say b is equal to 7 because 2 seconds later, the variable b is equal to 7, then why a has a different behaviour than b ?

Franck
  • 71
  • 1
  • 2
  • 2
    b is a global variable which is counted up by your for loop (always the same variable b). a is declared in your for loop, so for each iteration you get a new instance of a with a new value. This instance can be used inside your for loop and is bound to your anonymous function that is passed to setTimeout. Check out MDN for details on let: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – glutengo Dec 08 '17 at 23:16

1 Answers1

1

The difference is how scoped variables work with the let keyword. In this case, you are defining a new a for each iteration of the loop. But it is the same b variable for every iteration.

The timeouts don't actually start firing until after the loop ends. By this time, each timeout function scope was given a different a, but are grabbing the same final value of b.

Nathan
  • 505
  • 2
  • 8