What is Hoisting in JavaScript

Keesha Hargrove
2 min readDec 25, 2021

Hoisting — In JS, all declarations are defined at the top of the scope before any code is executed. As a result of hoisting, we can call functions before they are inserted into a program. Hoisting only applies to declarations, not to initializations.

JavaScript Hoisting: Understanding it in detail:

Following are the steps involved in declaring and initializing variables:

// Variable lifecycle
let x; ……….…………….// Declaration
x = “hoisting”; …………// Assignment
console.log(x); // Usage

The most common pattern, however, is using both declarations and initialization of variables simultaneously, since JavaScript allows both:

//let x = “hoisting”;

It’s important to remember that JavaScript always declares variables first. After that, they are initialized. Therefore, it’s also important to keep in mind how variable declarations are processed before any code is executed. In JavaScript, undeclared variables do not exist until the assignment code is executed.

In this case, the value assigned to an undeclared variable is implicitly created as a global variable when the assignment is executed. The undeclared variables become global variables in this case.

// hoisting
function Hoisting(){
x = 300;
let y = 400;
}
Hoisting();
console.log(x); // 300
console.log(y); // Reference Error: y is not defined

A function named Hoisting() appears in the sample code above. Therefore, we have a variable that was not declared using let/var/const and a let variable y. JavaScript assigns an undeclared variable to the global scope. We receive a ReferenceError for variable y.

Hoisting classes

in JavaScript can be divided into two categories:

  • Class declarations
  • Class expressions

In Class declarations

function equivalents are used in much the same way. Consequently, JavaScript class declarations are not hoisted. The classes remain untouched until evaluated. Therefore, before you can use a class, it must be declared

In Class expressions

As such, no class expression need be hoisted, as they are like their counterparts in function calls.

In summary

Many developers are unaware of Hoisting. Some might also overlook its importance. Furthermore, programs may contain errors (bugs) if the developer does not understand it. JavaScript interprets the code this way, so declaring all variables at the beginning of each scope will prevent any bugs from happening.

--

--