JS Hoisting
Hoisting is JavaScript's habit of "lifting" declarations to the top of their scope before executing code. The detail matters because it affects what's visible where.
What gets hoisted
| Declaration | Name hoisted? | Initialised to… |
|---|---|---|
function foo(){…} | Yes | The whole function — callable above its definition. |
var x = 1 | Yes | undefined until the assignment runs. |
let x = 1 | Yes | In the Temporal Dead Zone until the line is reached. |
const x = 1 | Yes | Same as let — TDZ. |
class Foo {} | Yes | In the TDZ. |
const fn = () => {} | Variable yes; function value no. | TDZ until the assignment runs. |
Examples
JS — function declaration hoists
greet(); // "Hello!" ✓
function greet() { console.log("Hello!"); }
JS — let/const are in TDZ
console.log(x); // ReferenceError ✗ let x = 5;
JS — var is hoisted as undefined
console.log(y); // undefined (not an error) var y = 5;
The Temporal Dead Zone (TDZ)
From the start of the enclosing block to the actual declaration, let and const exist but can't be read or written. Accessing them throws a ReferenceError. That's the spec's way of telling you to declare variables before using them.
Tip: Don't rely on hoisting. Declare functions and variables before you use them — the code reads top-to-bottom and the engine's lifting becomes irrelevant.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Hoisting!";
</script>
</body>
</html>
Try it Yourself »
Exercise
The error you get when accessing a let before its declaration is called…
Answer:
Dead Zone
Eight letters, time-related.
Discussion
Loading…