Javascript Hoisting

ยท 338 words ยท 2 minute read

Hoisting is a behavior in Javascript where the declaration of a variable, function or a class goes to the top of the scope where it was declared.

For example, the following code works without an error:

helloWorld()
// Hello, world!

function helloWorld(){
    console.log("Hello, world!")
}

Here, helloWorld() function is executed before it was declared. Before the interpreter starts executing, it hoists (brings up, lifts) the declaration code to the top.

Here are a few important nuances to consider about hoisting.

Hoisting Within Scope ๐Ÿ”—

Hoisting brings up function within the scope it was defined. For example,

printOne()
// One

printTwo()
// ReferenceError: printTwo is not defined

function printOne() {
  console.log('One')

  function printTwo() {
    console.log("Two")
  }
}

Here, printTwo() throws ReferenceError because the function is hoisting within the scope of printOne() For this reason, the following code works fine.

printOne()
// One

function printOne() {
    printTwo()
    // Two

  console.log('One')

  function printTwo() {
    console.log("Two")
  }
}

Hoisting var Variables ๐Ÿ”—

For variables that are defined with var, the variable declaration is hoisting with a default value of undefined. For example,

console.log(myVar)
// undefined

var myVar = 'Here is my var'

Without hoisting, we would get a ReferenceError.

console.log(theVar)
// ReferenceError: theVar is not defined

var myVar = 'Here is my var'

Although the hoisting is happening, the value of the variable is not accessible before declaration.

Hoisting let And const Variables ๐Ÿ”—

The variables that are defined with let and const are also hoisted just like the variables defined with var, except one key difference: they do not get the default value of undefined. For example:

console.log(myVar)
// ReferenceError: Cannot access myVar before initialization

let myVar = 'Here is my var'

Hoisting Classes ๐Ÿ”—

Classes in Javascript are hoisting just like let and const variables. They cannot be accessed until declared.

Temporal Dead Zone (TDZ) ๐Ÿ”—

The variables declared with let and const, and the classes in Javascript, are hoisting to the top of the scope, but they are not accessible until they are declared. This concept is known as the Temporal Dead Zone (TDZ)