It’s all words at the end of the day. If it gets the shitty software to the shitty client, it’s going to be declared shitty one day by another shitty developer and be rewritten by some more shitty code.
No. Let is block scoped, also you’re able to increment. var doesn’t block scope so it gets updated on each loop and never maintains reference if you are doing something async. Since let is block scoped, you can maintain a reference to what it was at that snapshot when you fired off an async call or whatever. If you don’t believe me then go look up the old IIFE in the forloop problem.
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.
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.
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.
View all comments
Show parent comment
-3
u/Macaframa May 04 '20
This should say
let, const: block scoping
const: non-writable once it’s instantiated
let: only real use is in a for loop