iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

DeclarationName hoisted?Initialised to…
function foo(){…}YesThe whole function — callable above its definition.
var x = 1Yesundefined until the assignment runs.
let x = 1YesIn the Temporal Dead Zone until the line is reached.
const x = 1YesSame as let — TDZ.
class Foo {}YesIn 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

Test yourself

Q1. Function declarations are hoisted with…
Q2. Accessing a `let` before its declaration throws because of…
Q3. `var` hoisting initializes the variable to…

Discussion

Loading…