</>
Skip to content
JavaScript lessons (42/64)

JavaScript — Hoisting

The illusion

Using a function before its definition works:

sayHi();                       // "Hi!" — runs fine!

function sayHi() {
    console.log("Hi!");
}

JavaScript's two-pass reading: it scans all declarations first (hoisting), then executes. Declarations are registered early; assignments are not.

What actually hoists

DeclarationBehavior before its line
functionfully usable ✓
varexists as undefined
let / constexist but unusable (TDZ)
classunusable like let
console.log(a);   // undefined 😕
var a = 5;

console.log(b);   // ReferenceError!
let b = 6;

Temporal dead zone (TDZ)

Between block start and the let/const line, the variable exists but can't be touched:

{
    // TDZ for x starts here
    // console.log(x) would throw
    const x = 1;    // TDZ ends
}

This is a safety feature: bugs surface loudly instead of silently being undefined.

Only declarations, never initializers

var name = "Ada";
// becomes effectively:
// var name;          ← hoisted
// name = "Ada";      ← stays put, runs in order

console.log(name);    // undefined if read before assignment line

Function expressions vs declarations

run();     // TypeError: run is not a function (var holds undefined)
var run = () => "go";

jump();    // works — real declaration
function jump() { }

The arrow stored in a variable follows variable rules, not function-declaration rules. This trips people constantly when reordering code.

Practical takeaways

  1. Declare at top of scope — hoisting knowledge becomes irrelevant
  2. Prefer let/const so accidental early reads throw instead of whisper undefined
  3. Function declarations may sit below callers safely (common in module files)

Mini Practice

  1. Call-before-define both styles; compare error messages
  2. Log a var before its line; log a let — contrast outcomes
  3. Reorder an arrow-function callback to prove the TypeError case
  4. Sketch on paper what two-pass execution means for a 5-line script

Next: strict mode →

Related Topics

Frequently Asked Questions about Hoisting

What is Hoisting in JavaScript?

Hoisting is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Hoisting?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Hoisting.

Why is Hoisting important in JavaScript?

Hoisting is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.