4

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 ?
thelonglqd
  • 1,805
  • 16
  • 28
  • There's two `i`s; the `for` loop counter you can see, and an invisible `inner.i = for_loop.i` that is used by the code inside the loop. – Ken Y-N Oct 28 '20 at 06:28
  • @KenY-N: Where could I find this information ? ebook or any tutorial ? Would you mind if represent what you said in pseudo code ? – thelonglqd Oct 28 '20 at 06:30
  • From the book you quote, just a little [further down the page](https://books.google.co.jp/books?id=rec6CwAAQBAJ&lpg=PA12&ots=RNO9j0Xyln&pg=PA12#v=onepage&q=The%20let%20i%20in%20the%20for%20header%20declares%20an%20i%20not%20just%20for%20the%20for%20loop%20itself,%20but%20it%20redeclares%20a%20new%20i%20for%20each%20iteration%20of%20the%20loop&f=false) is sample code. – Ken Y-N Oct 28 '20 at 06:41
  • Honesly, I read this code, but I saw it used `let` so I think it does not make any sense, but I've just retried with `var j= i`, it works, thanksssss. It answered my second problem but how about the first ? – thelonglqd Oct 28 '20 at 06:47
  • The `i` of the current iteration is initialized with the value of `i` of the previous iteration. – Felix Kling Oct 28 '20 at 07:26

0 Answers0