Skip to content
YouTurkey Tech
All JavaScript topics

Hoisting

Beginner

Why you can call a function before its line, but reading a let too early throws an error.Builds on Execution Context

Call stack

Empty

Scopes

Empty

Heap

Empty

Console

Empty

0/13Press Play, or step through with the arrows, to begin.
Step 0 of 13

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 x holds undefined.
  • let x and const x are uninitialized. Reading them throws a ReferenceError.

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
  1. Step 1:

    Before running anything, JavaScript scans the code and sets up memory for every declaration. This creation phase is where hoisting happens.

  2. Step 2:

    var count is hoisted and set to undefined. The = 5 part stays on line 4.

    Line 4

  3. Step 3:

    The function declaration sayHi is hoisted completely, body included.

    Lines 7–9

  4. Step 4:

    let total is hoisted too, but left uninitialized. Until line 12 runs, it is in the temporal dead zone (TDZ).

    Line 12

  5. Step 5:

    Memory is ready. Now the code runs from the top, line by line.

  6. Step 6:

    count already exists, so reading it works. It is still undefined, and that is what gets printed.

    Line 1

  7. Step 7:

    sayHi() can be called before its line because the whole function was hoisted. Its context goes on the stack.

    Line 2

  8. Step 8:

    return 'Hi!' ends the call: its context leaves the stack.

    Line 8

  9. Step 9:

    Back on line 2, console.log prints the returned Hi!

    Line 2

  10. Step 10:

    Now the assignment on line 4 runs: count becomes 5.

    Line 4

  11. Step 11:

    This time console.log(count) prints 5.

    Line 5

  12. Step 12:

    total exists, but it is still in the TDZ. Reading it throws a ReferenceError.

    Line 11

  13. Step 13:

    The uncaught error stops the script. Line 12 never runs, so total is never initialized.

    Line 12