Learn JavaScript
❯ variables.hoisting

Hoisting in JavaScript

$concept

Hoisting moves declarations (not initializations) to the top of their scope before execution: var declarations and function declarations are usable-above-their-line (vars as undefined), while let/const live in the temporal dead zone until their line runs. This isn't physical code motion — the engine simply creates bindings during a setup pass.

Practical fallout: call functions before defining them freely (function declarations hoist fully), never rely on pre-line var values (undefined, not errors), and expect ReferenceErrors — not undefined — from early let/const access.

$how it works
1

Declarations lift, values don't

var x; lifts so x reads undefined above; x = 5 stays where written — setup pass creates bindings, execution assigns.

2

Functions hoist whole

function f() {} is defined before any line runs — calling f() at the file top works.

3

let/const wait in the TDZ

Their bindings exist but throw on access until the declaration line executes — safer than var's silent undefined.

4

Write as if none existed

Declare before use anyway — code readable without hoisting knowledge beats code exploiting it.

$example
console.log(greet("Ada"));
function greet(name) {
return "hi " + name;
}
console.log(typeof later);
var later = 1;
Output
hi Ada
undefined
1greet is fully hoisted, so calling it on line 1 works — hi Ada prints.
2var later lifts as undefined, so typeof later reads undefined without throwing.
3Had later been let, the same line would throw a TDZ ReferenceError instead.
$use cases
Calling helper functions above their definitions safely
Understanding undefined-vs-ReferenceError in legacy var code
Preferring let/const so mistakes throw instead of silently undefining
Explaining interview questions about pre-declaration access

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.