ES6 Notes: let and const
Notes adapted from Ruan Yifeng's ES6 introduction. This part covers let and const.
~/posts/es6-let-and-const $ cat post.md
Adapted from Ruan Yifeng’s ES6 入门, mostly as study notes for myself.
Overview
Unlike var, let is scoped to its enclosing block — for example, a
for loop:
for (let i = 0; i < 1; i++) {}
let avoids the classic var problem where i is still readable
outside the loop with whatever value it ended on.
Scope
In a for statement, the loop header and the loop body are different
scopes:
for (let i = 0; i < 3; i++) {
let i = "abc";
console.log(i);
}
This logs "abc" three times — the i inside the body is a fresh
binding.
Hoisting
let is not hoisted. var declarations, on the other hand, are
created as undefined before the code runs and only get their assigned
value when the declaration line executes:
// var
console.log(foo); // undefined
var foo = 2;
// let
console.log(bar); // ReferenceError
let bar = 2;
Above, foo is reachable as undefined before its declaration line —
that’s hoisting.
Temporal dead zone (TDZ)
var tmp = 123;
if (true) {
tmp = "abc"; // ReferenceError
let tmp;
}
Until the let tmp declaration executes, tmp inside the block is
inaccessible.
var tmp = 123;
if (true) {
tmp = "abc"; // OK
}
If the block doesn’t redeclare tmp with let, references inside the
block read and write the outer tmp normally.