How the for loop with let works in detail?

Viewed 52

The post title might confuse you guys but here what I want to understand:

Typically, the for loop runs this way

// for (let i = 0; i < 3; i++) alert(i)

// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3

But, the let will redeclare for each iteration, qoute from YDKJS:

The let i in the for header declares an i not just for the for loop itself, but it redeclares a new i for each iteration of the loop. That means that closures created inside the loop iteration close over those per-iteration variables the way you'd expect.

So my problem is,

  1. While i is always redeclared, how it knows that it used to be incremented ? How the redeclaration statement looks like ? let i = ???;
  2. What can I do to polyfill this behavior with var, I found out I can use closure to save the i value for each iteration but is it overwhelming ?
0 Answers
Related