1

Why i behaves differently in arrow functions? Is it because var x is being reassigned while let x is being created new for each iteration?

//prints 55555
for(var x = 0; x < 5;x++){
    setTimeout(()=>console.log(x),0);
}

//prints 01234
for(let x = 0;x < 5;x++){
    setTimeout(()=>console.log(x),0);
}
Eli Richardson
  • 934
  • 7
  • 25
Manu Chadha
  • 15,555
  • 19
  • 91
  • 184

2 Answers2

1

It has nothing to do with arrow functions. let is block level scope, so each time you enter the body of the loop, you get a new variable.

In your case, the timer function prints differently, because of the closure being created around x.

var provides one variable that all iterations of the loop (and therefore, all timer callbacks) share, hence you get the last value of the variable shared by each timer callback. Remember, the timer callbacks won’t run until your loop is finished and, at that time, x has been incremented to 5.

let gives each timer callback it’s own value because of the block scope. So, even though the timer callbacks don’t run until the loop is finished, each callback has a closure around a differently scoped variable.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

let in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration, so it can be used to avoid issue with closures.

Read more here: http://www.jstips.co/en/javascript/keyword-var-vs-let/

Bartosz Herba
  • 343
  • 2
  • 7