let, const, and the Temporal Dead Zone
let and const fixed the problems var created, but they introduced a new concept: the Temporal Dead Zone, where variables exist but cannot be touched.
let and const are hoisted but stay in the TDZ until their declaration line. Accessing them before that throws a ReferenceError. const must be initialized when declared.
EXERCISE
1let and const: The Strict Cousins of var
var was the original way to declare variables in JavaScript, but it had too many surprises. let and const were added in ES6 to make variables behave more predictably.
var has three behaviours that cause bugs, and let and const exist to remove all three. var is scoped to the whole enclosing function rather than to the block it sits in. It can be redeclared with the same name silently, overwriting what was there. And it can be read before the line that declares it, handing back undefined instead of complaining. None of those is a style preference: each has a failure mode you will meet in real code.
Block scope is the first difference, and the one you will notice most:
if (true) {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceError: b is not defined
a escaped the if block because var does not recognise blocks at all, only functions. b did not, because let is scoped to the nearest pair of braces. The second behaviour is what almost everyone assumes is happening, which is precisely why var surprises people.
Redeclaration is the second:
var name = "first";
var name = "second"; // fine, silently replaced
let title = "first";
let title = "second"; // SyntaxError: Identifier 'title' has already been declared
The var version is legal and produces no warning. In a long function, or after a careless merge, that is a variable being overwritten by code that believed it was creating a new one. let makes it a syntax error, caught before the file runs at all.
const adds one more rule: the binding cannot be reassigned.
const rate = 0.2;
rate = 0.3; // TypeError: Assignment to constant variable
Note what that does and does not promise. It protects the binding, not the value. A const object can still have its properties changed, and a const array can still be pushed to. What you cannot do is point the name at something else. That distinction catches people constantly, and it is the subject of the next exercise but one.
The practical rule most teams settle on: reach for const first, switch to let when you genuinely need to reassign, and treat var as something you read in older code rather than write in new code.
EXERCISE
2The Temporal Dead Zone (TDZ)
let and const ARE hoisted, but they sit in a special danger zone between hoisting and initialization. Access them in this zone and JavaScript throws an error.
let and const are still processed during the memory phase, and their slots are created before any code runs, exactly like var. The difference is what is in the slot. A var slot holds undefined and can be read. A let or const slot is marked unreadable until execution reaches its declaration line, and reading it before then throws.
The region between the top of the block and the declaration line is called the Temporal Dead Zone, usually shortened to TDZ. "Temporal" because it is about time, not position: the same line of code is safe or unsafe depending on when it runs.
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
Compare the error to the one you get for a name that does not exist at all:
console.log(ghost); // ReferenceError: ghost is not defined
Both are ReferenceError, but the messages differ and the difference is informative. Cannot access before initialization means the engine found the declaration and is refusing to let you read it early. Is not defined means it found no declaration anywhere. The first is a fixable ordering problem in code you wrote; the second is usually a typo or a missing import.
The zone is bounded by the declaration, not by the assignment:
{
// TDZ for `value` starts here
console.log(typeof value); // throws, even though typeof is normally safe
let value = 1;
// TDZ ends; `value` is readable from here on
}
That line is worth pausing on. typeof tolerates completely undeclared names, which is what makes it useful for feature detection, but it does not tolerate the TDZ. This is the one case where typeof throws.
The TDZ exists to turn a silent bug into a loud one. With var, reading a variable too early gives you undefined, which flows onward and fails somewhere else entirely. With let, it fails at the line that made the mistake.
Pro Tip: The TDZ is why "hoisting" is a misleading word for
letandconst. They are hoisted, in the sense that their slots exist from the start of the block. What changed is that the engine now refuses to let you use one before its declaration, rather than handing youundefinedand letting you find out later.
EXERCISE
3Three Types of Errors You Must Know
JavaScript throws different types of errors for different mistakes. Knowing which error belongs to which situation makes debugging 10x faster.
Three error types account for most of what throws at you, and each one points at a different kind of mistake. Learning to read them is faster than learning to debug them.
ReferenceError: the name could not be resolved. Either it was never declared, or it is a let or const being read inside its Temporal Dead Zone:
console.log(nope); // ReferenceError: nope is not defined
console.log(later); // ReferenceError: Cannot access 'later' before initialization
let later = 1;
TypeError: the name resolved fine, but the value cannot do what you asked. Calling something that is not a function, or reading a property of undefined or null:
var notAFunction = 5;
notAFunction(); // TypeError: notAFunction is not a function
var user;
console.log(user.name); // TypeError: Cannot read properties of undefined
Both lines found their variable. The complaint is about the value in it, which is why this class of error usually means your data is not the shape you expected rather than your spelling is wrong.
SyntaxError: the code is not valid JavaScript, so none of it runs:
let dup = 1;
let dup = 2; // SyntaxError: Identifier 'dup' has already been declared
This one is different in kind from the other two. A SyntaxError of this sort is thrown before execution begins, so nothing in the file runs at all, not even the lines above the mistake. If a whole module appears to do nothing, this is worth checking first.
Put the three together as a diagnostic:
| Message | What it means | Where to look |
|---|---|---|
x is not defined | no declaration in scope | spelling, imports, scope |
Cannot access 'x' before initialization | read inside the TDZ | order of statements |
x is not a function | value is not callable | what was assigned to x |
Cannot read properties of undefined | you indexed into nothing | where the object should have come from |
Identifier 'x' has already been declared | duplicate let/const | the whole file is not running |
Pro Tip: Read the error before reading the code. The message names both the failing identifier and the category of failure, which together usually narrow the cause to one or two lines. Most time lost to debugging is spent looking for something the error had already said.
