Hoisting
BeginnerWhy you can call a function before its line, but reading a let too early throws an error.Builds on Execution Context
Empty
Empty
Empty
Empty
Spaceplay or pause←→previous or next stepRback to the start
Explanation
2 min read
On this page
What is hoisting in JavaScript?
Put simply, hoisting is what the looks like from your code's point of view. Before a scope runs, JavaScript registers every declaration in it, so some names can be used before the line that declares them. Nothing is physically moved: the declarations are simply known in advance.
What does a name hold before its line runs?
What a name holds before its line depends on how it was declared:
function f() {}holds the whole function, ready to call.var xholdsundefined.let xandconst xare uninitialized. Reading them throws aReferenceError.
The stretch between the start of the scope and a let/const line is the
(TDZ). The name exists there, but you cannot touch it yet.
What mistakes do people make with hoisting?
Mini example
console.log(typeof hello); // 'function'console.log(x); // undefinedconsole.log(y); // ReferenceError function hello() {}var x = 1;let y = 2;Quick check
What does the second line, console.log(x), print?
Further reading
Watch the video
The full explanation from the YouTurkey Tech YouTube channel, in Arabic.
All steps as text
- Step 1:
Before running anything, JavaScript scans the code and sets up memory for every declaration. This creation phase is where hoisting happens.
- Step 2:
var countis hoisted and set to undefined. The= 5part stays on line 4.Line 4
- Step 3:
The function declaration
sayHiis hoisted completely, body included.Lines 7–9
- Step 4:
let totalis hoisted too, but left uninitialized. Until line 12 runs, it is in the temporal dead zone (TDZ).Line 12
- Step 5:
Memory is ready. Now the code runs from the top, line by line.
- Step 6:
countalready exists, so reading it works. It is still undefined, and that is what gets printed.Line 1
- Step 7:
sayHi()can be called before its line because the whole function was hoisted. Its context goes on the stack.Line 2
- Step 8:
return 'Hi!'ends the call: its context leaves the stack.Line 8
- Step 9:
Back on line 2, console.log prints the returned Hi!
Line 2
- Step 10:
Now the assignment on line 4 runs:
countbecomes 5.Line 4
- Step 11:
This time
console.log(count)prints 5.Line 5
- Step 12:
totalexists, but it is still in the TDZ. Reading it throws a ReferenceError.Line 11
- Step 13:
The uncaught error stops the script. Line 12 never runs, so
totalis never initialized.Line 12