-1

I am copying an excerpt from Javascript post. Need to know what exactly author is trying to convey.

In loops, you get a fresh binding for each iteration if you let-declare a variable. The loops that allow you to do so are: for, for-in and for-of.

This looks as follows:

let arr = [];
for (let i=0; i < 3; i++) {
    arr.push(() => i);
}

console.log(arr.map(x => x())); // [0,1,2]

In contrast, a var declaration leads to a single binding for the whole loop (a const declaration works the same):

let arr = [];
for (var i=0; i < 3; i++) {
    arr.push(() => i);
}

console.log(arr.map(x => x())); // [3,3,3]

Getting a fresh binding for each iteration may seem strange at first, but it is very useful whenever you use loops to create functions (e.g. callbacks for event handling) that refer to loop variables.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Sagar
  • 19
  • 6
  • 5
    The author explains it pretty properly. What is your exact question about this? – ssc-hrep3 Oct 16 '18 at 07:09
  • I was trying to understand binding. Got the answer from https://stackoverflow.com/questions/31285911/why-let-and-var-bindings-behave-differently-using-settimeout-function – Sagar Oct 16 '18 at 10:33

1 Answers1

0

Basically let makes a new variable each loop so the array it's pushed to won't have the same value in each index as it would with var since all index arrays would point to the same variable.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Edward Lynch
  • 148
  • 8