Hoisting - JavaScript Concepts Simplified

Hoisting - JavaScript Concepts Simplified

Have you ever wondered how you are able to call a function in JS even before declaring it? JavaScript is an interpreted programming language. An interpreter in the browser interprets each line of code and runs it. The interpreter follows a process called Hoisting to make the aforementioned feature possible.

What is Hoisting

Hoisting is the process of moving the declarations of functions, variables and classes to the top of their scope before the code is executed. Let's discuss each one of these scenarios with examples.

Function Hoisting

//Before hoisting 
thisIsHuge()    //Logs "That's what she said" to the console 
function thisIsHuge(){ 
    console.log('That\'s what she said') 
}

Since the function is declared in the global scope, the interpreter moves the declaration of the function to the top of the code by hoisting

function thisIsHuge(){ 
    console.log('That\'s what she said') 
} 
thisIsHuge()

Variable Hoisting

There are 3 keywords that we can use to declare a variable in JS: var, let and const. Let's see how hoisting works for each one of them.

//Using var keyword
console.log(x) //Logs undefined to the console (Default initialization of var) 
var x = 10
console.log(x) //Logs 10 to the console

//Using let keyword
console.log(y)  //Throws ReferenceError: Cannot access 'y' before initialization
let y = 20

//Using const keyword
console.log(z)  //Throws ReferenceError: Cannot access 'z' before initialization
const z = 30

Variables declared using let and const keywords do not have a default initialization value.

class Hoisting

Even though, we can call a function before it is defined, we cannot construct an object before the class is defined.

console.log(new Car()); //ReferenceError: Cannot access 'Car' before initialization

class Car {
  constructor(name, year) {
    this.name = name;
    this.year = year;
  }
}

Summary

It is always a good coding practice to declare the variables at the top of the scope

It's true that hoisting can be useful sometimes. But in the long run, it will end up creating more bugs. We should always declare the variables, classes and functions before using them.

Further Reading

Ciao

Thank you for reading my article. I hope you learned something valuable today. If you liked it, drop a like and subscribe to my blog. I’ll see you soon with my next article. Stay Safe 😷