Hoisting in Javascript

·

2 min read

Hoisting in Javascript

In JavaScript, hoisting allows you to use functions and variables before they're declared.

When the JavaScript engine executes the JavaScript code, it creates the global execution context. The global execution context has two phases:

  • Creation

  • Execution

During the creation phase, the JavaScript engine moves the variable and function declarations to the top of your code. This is known as hoisting in JavaScript.

Variable Hoisting

Variable hoisting means the JavaScript engine moves the variable declarations to the top of the script.

console.log(greet);  // undefined
var greet = "Hello";

This code doesn't throw any errors because the JavaScript engine moves the variable declaration to the top of the script. This is "Hoist".

Technically, the code looks like the following in the execution phase. During the creation phase of the global execution context, the var greet will be placed in memory and an undefined value is assigned.

var greet;
console.log(greet);  // undefined
greet = "Hello";

But this is not the same case for let variables. The JavaScript engine hoists the variable declarations that use the let keyword. However, it doesn’t initialize the let variables. Same for const too.

console.log(greet);  // ReferenceError: Cannot access 'counter' before initialization
let greet = "Hi";

So, let and const works differently with javascript hoisting. This is because let and const variables have a different scope than var variables. (Check var, let and const blog...)

Function Hoisting

Like variables, the JavaScript engine also hoists the function declarations. This means that the JavaScript engine also moves the function declarations to the top of the script.

getName();
function getName() {
    console.log("ABC")  // "ABC"
}

Although, Hoisting does not work with a function expression and arrow function. Here is an example.

getName();

let output = function getName() {
    console.log("ABC")  // ReferenceError: getName is not defined
}

console.log(output);

Here we assigned the getName() to output variable. During the creation phase of the global execution context, the JavaScript engine creates the output variable in the memory and initializes its value to undefined.

We will face the same error while we are using the arrow function.

getName()
function getName() {
    console.log("Hey")  // Hey
}

getAddress();
const getAddress = () => {
    console.log("Earth")  // ReferenceError: Cannot access 'getAddress' before initialization
}

Summary

  • JavaScript hoisting occurs during the creation phase of the execution context that moves the variable and function declarations to the top of the script.

  • The JavaScript engine hoists the variables declared using the let and const keyword, but it doesn’t initialize them the same as the variables declared with the var keyword.

  • The JavaScript engine doesn’t hoist the function expressions and arrow functions.