Sub topic 2
Hoisting: What Happens Before Your Code Runs
This chapter assumes you know the basic syntax of var, let, and const. It also assumes you know that var is function-scoped and that let and const are block-scoped.
Hoisting
Before any code in a scope runs, the JavaScript engine registers every declaration in that scope. This is called hoisting. The keywords differ in what happens to the variable at that point. A var is created and set to undefined straight away. A let or const is created but stays uninitialized until the engine reaches its declaration line.
console.log(x); // undefined: var is hoisted and initialized to undefined
var x = 5;
try {
console.log(y); // y exists but is not initialized yet
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let y = 10;The Temporal Dead Zone
The temporal dead zone (TDZ) is the stretch of time between the start of a scope and the line where a let or const declaration runs. If you read or write the variable during that time, you get a ReferenceError. The TDZ is a matter of when code runs, not where it sits in the file. A function that reads a let variable works fine if you call it after the declaration has run.
Redeclaring and Reassigning
| Keyword | Redeclare in same scope | Reassign |
|---|---|---|
| `var` | Allowed | Allowed |
| `let` | SyntaxError | Allowed |
| `const` | SyntaxError | TypeError |
var a = 1;
var a = 2; // allowed
console.log(a); // 2
const c = 1;
try {
c = 2;
} catch (e) {
console.log(e.name); // 'TypeError'
}Redeclaring with let or const fails at parse time, so none of the script runs. Reassigning a const fails only when that line executes.
const Does Not Mean Immutable
const locks the binding, meaning the link between the name and a value. It does not lock the value. You can still change an object or array declared with const. To stop changes to an object's own properties, use Object.freeze.
const config = { retries: 3 };
config.retries = 5; // allowed: the object is mutable
console.log(config.retries); // 5
function tryFrozen() {
'use strict';
const frozen = Object.freeze({ retries: 3 });
try {
frozen.retries = 5;
} catch (e) {
console.log(e.name); // 'TypeError'
}
}
tryFrozen();Exercise
What does this log, and why? function f() { return n; } let n = 1; console.log(f());
Show answer
It logs 1. f is called after the let n = 1 declaration has run, so n is out of its temporal dead zone. The TDZ depends on when code executes, not on where the code appears in the file.
Exercise
Given const list = [1, 2];, which line throws: list.push(3); or list = [1, 2, 3];?
Show answer
list = [1, 2, 3]; throws a TypeError because it reassigns the const binding. list.push(3) changes the array itself, which is allowed.