Skip to main content

hoisting

What is hoisting

Hoisting is a JavaScript mechanism in which variable and function declarations are "moved" to the top of the scope (before the code executes).

But it's important: only declarations are hoisted, not value assignments.


1. Function Declaration - can be called before declaration

javascript
sayHi(); // Works! function sayHi() { console.log("Hello!"); }

Why it works:

  • During the preparation phase, the interpreter finds function sayHi and creates the function in advance in memory.
  • When the code executes line by line, the function is already available.

Result:

javascript
Hello!

2. Function Expression - does not work

javascript
sayHi(); // TypeError: sayHi is not a function const sayHi = function() { console.log("Hello!"); };

Why it does not work:

  • const sayHi is hoisted (hoisting exists), but only the variable declaration itself, without assigning the function.
  • Before the initialization line, sayHi is in the "temporal dead zone" (TDZ).
  • Accessing it before assignment causes an error.

3. Arrow Function - the same thing

javascript
greet(); // TypeError: greet is not a function const greet = () => console.log("Hello!");

Why:

  • Arrow functions are function expressions, just with different syntax.
  • So the behavior is the same: the variable is unavailable until it is assigned.

4. var + function expression - a special case

javascript
sayHi(); // TypeError: sayHi is not a function var sayHi = function() { console.log("Hello!"); };

What happens:

  • The variable sayHi is hoisted (hoisting with var), but it is assigned the value undefined before the line with the function executes.
  • At the moment of calling sayHi(), it is undefined, not a function, so it errors.

Quick summary

Declaration methodCan it be called before declaration?Why
function declarationYesThe function is fully "hoisted"
function expression (const/let)NoThe variable is in the TDZ
function expression (var)NoThe variable is undefined before assignment
arrow functionNoSame as function expression

Visualizing hoisting

javascript
// Roughly what happens inside the JavaScript engine: function sayHi() { console.log("Hello!"); } // fully hoisted var sayBye; // hoisted, but without a value sayHi(); // works sayBye(); // error (undefined) sayBye = function() { console.log("Bye!"); };

Summary

Function Declaration functions are created in advance and available in the whole scope. Function Expression and Arrow Function are not - they can only be called after declaration.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.