Hoisting in JavaScript

0

Introduction

Hoisting is a behavior with which JavaScript, right before it start to execute the code, add all the variables, constants, functions and Classes declaration into memory. This gives a feeling that all the declarations are hoisted or already declared, specially “var” and “function”.

Hoisting affects Classes, variables and functions differently.

Hoisting variables and constants in JavaScript

For variables and constants, JavaScript reserve space in memory. For var, it assign a placeholder value undefined and attached to global scope but let and const remain in temporal dead zone and not accessible until initialized.

Example var :

When we run the following code, for first console it will give us undefined and for second console, it will give us the value assigned.

console.log(myName ); // Prints undefined, as undefined value is assigned in memory before code execution
var myName = "Sahil";
console.log(myName ); // Prints "Sahil" as Sahil value is assigned in code above

Example let and const :

When we run the following examples, this code will not run because there is no placeholder value assigned in memory during hoisting for let and const.

console.log(myName ); // ReferenceError: Cannot access 'name' before initialization
const myName = "Sahil";
console.log(myName ); // ReferenceError: Cannot access 'name' before initialization
let myName = "Sahil";

Hoisting functions in JavaScript

Function are hoisted in JavaScript, complete function declaration is copied into memory but when function is defined with function keyword. We can define functions in three different ways, function keyword, function expression and arrow function.

While all the work almost the same way but they differ when they are hoisted.

Example : function keyword

When we define a function with function keyword in JavaScript, it is hoisted and all its code is as it is copied into memory even bore execution. In the code below, we are able to use the function even before its definition because it is already hoisted and saved into memory.

printName("Sahil"); // print Sahil, because already exists in memory due to hoisting
function printName(name){
  console.log("Sahil");
}

Example : function expression

We can create variable with var, let and const and assign function declaration to them. This way that variable will act as function. But this does not work in same manner when it comes to hoisting. JavaScript treat these type of functions as variables and does not copy full definition into memory while hoisting. All three codes below will give errors.

printName("Sahil"); // print Error, because no definition in memory due to hoisting
var printName = function (name){
  console.log("Sahil");
}
printName("Sahil"); // print Error, because no definition in memory due to hoisting
let printName = function (name){
  console.log("Sahil");
}
printName("Sahil"); // print Error, because no definition in memory due to hoisting
const printName = function (name){
  console.log("Sahil");
}

Example : Arrow function

Arrow function in JavaScript are also hoisted in JavaScript but their definition is not copied in memory, so these cant be use before the definition code executes. The following code example trying to call the arrow function before its definition will give error.

printName("Sahil"); // print Error, because no definition in memory due to hoisting

const printName = (name) => {
  console.log("Sahil");
}

Hoisting classes in JavaScript

Classes are hoisted in JavaScript but their definition is not copied into memory before its definition code is run. So if we try to print the class definition before its definition, or we try to create and instance of class before its definition, it will give us an error. Below code will not run doe to the same reason.


console.log(Name);// throw error because class deinition found in memory
let obj = new Name("Sahil","Ahlawat");// throw error because class deinition found in memory
console.log(obj.firstName,obj.lastName);// throw error because class deinition found in memory
class Name {
    constructor(firstName, lastName) {
      this.firstName = firstName; this.lastName = lastName;
    }
}

Video explanation of hoisting in English

Video explanation of hoisting in Hindi

Conclusion

Hoisting is JavaScript can impact the code in different manner, we should try to use use variable, functions and classes only after their definition to avoid any errors or unexpected behaviour.

Leave a Comment

Skip to content