let, const and the dead zone in JavaScript
Block scoping, and why a let is unusable before its declaration.
function scoping() {
const results = [];
if (true) {
var leaks = "function scoped";
let contained = "block scoped";
results.push(contained);
}
results.push(leaks);
try {
early;
let early = 1;
} catch (error) {
results.push(error.constructor.name);
}
const config = { theme: "dark" };
config.theme = "light"; // allowed: the binding is const, not the object
results.push(config.theme);
return results;
}
console.log(scoping());
How it works
letandconstare block-scoped;varis function-scoped.- Touching a
letbefore its line throws a ReferenceError. constfreezes the binding, not the object it points at.
Keywords and builtins used here
catchconstconstructorfunctionifletreturntryvar
The run, in numbers
- Lines
- 24
- Characters to type
- 430
- Tokens
- 106
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 80 seconds.
Step 2 of 5 in Bindings & values, step 2 of 43 in Language basics.