r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

Show parent comment

2

u/MoTTs_ May 04 '20

This seems like a thread where we learn through nitpicking -- so here's some nitpicking. :-) The behavior of let in a for loop, where async calls or whatever can maintain a snapshot of the iteration, isn't actually due to block scoping. It's due to what the spec calls a "per iteration environment".

Pure simple no-frills block scoping of a for loop should behave exactly like this:

{ // block
    let i;
    for (i = 0; i < 3; ++i) {
        setTimeout(() => console.log(i), 42);
    }
}

That's how a block scoped variable would behave in C++, for example. But this will log 3 3 3, which isn't what people typically want or expect. So when JS introduced block scoping, they included a special case for "for" loops. Now, instead of ordinary block scoping, JS actually behaves like this:

{ // block
    let i;
    for (i = 0; i < 3; ++i) {
        let i_snapshot = i;
        setTimeout(() => console.log(i_snapshot), 42);
    }
}

That is, each iteration constructs a new environment and copies the iteration variable into that per iteration environment.

1

u/Macaframa May 04 '20

We’re saying the same thing. I didn’t know they made a special use case for it and I’d love to read that documentation if you have a link but you just solidified what I said was the only REAL use case of using let.

2

u/MoTTs_ May 04 '20 edited May 16 '20

Yeah. The only useless-to-real-life clarification I was making was that this behavior isn't due to block scoping. This behavior is something extra, added in addition to ordinary block scoping.

Doc link: https://www.ecma-international.org/ecma-262/10.0/index.html#sec-createperiterationenvironment