ResourcesJavascriptGuides

hoisting

Introduction

Hoisting is a Javascript mechanism where variables and function declarations are moved to the top of their scope during the compilation phase.

This guide explains hoisting in depth and it will no longer be a confusing topic for you!

Before, make sure you understand what a scope is. We have article about it: Scope in Javascript


What is hoisting?

Hoisting allows you to use functions and variables before they are declared. In Javascript, declarations are hoisted to the top, but assignments are not.

If you don't know the difference between declarations and assignments we have an article about it: Declaration vs assignment

Basic example with variable hoisiting:

console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5

The declaration var x is hoisted to the top, but the assignment x = 5 is not.

There is a slight difference about hoisting var, let, const, we also have an article explaining the difference between those: Let, const and var

Function hoisting

Function declarations are hoisted entirely, allowing you to call functions before they appear in the code.

However, arrow functions are treated as variables and are not hoisted in the same way.

console.log(greet()); // Output: Hello, world!
 
function greet() {
  return "Hello, world!";
}

With arrow functions:

console.log(greetArrow()); // TypeError: greetArrow is not a function
 
const greetArrow = () => {
  return "Hello, world!";
};

Let and const hoisiting

Variables declared with let and const are hoisted but not initialized, leading to a ReferenceError if accessed before their declaration.

console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 10;
 
console.log(b); // ReferenceError: Cannot access 'b' before initialization
const b = 20;

Class Hoisting

Similar to let and const classes are hoisted but not initialized.

const instance = new MyClass(); // ReferenceError: Cannot access 'MyClass' before initialization
 
class MyClass {
  constructor() {
    this.name = 'MyClass';
  }
}

Hoisting in closures

The inner function is hoisted within the outer function, allowing it to be called before its declaration.

function outer() {
  console.log(inner()); // Output: Hello from inner
 
  function inner() {
    return "Hello from inner";
  }
}
outer();

Resources

MDN Web docs

On this page