Hoisting in JS

Hoisting in JS

JS hoisting can be referred to as the process where the interpreter moves all the declaration of the functions, variable and classes to the top of the code before the execution of the code.

Hoisting allows us to safely use the function's before they are declared.

Class and variable declarations are also hoisted. they also can be referenced before they are declared.

Function Hoisting The main advantage of this type of hoisting is that this lets you use the function before its even declared.

carName("Demo")

function carName(name) {
console.log(`This is my car name ${name}`)
}

// The output of the code is -> This is my car name demo

Without function hoisting we would have written this same code as

function carName(name) {
console.log(`This is my car name ${name}`)
}

carName("Demo")

// The output of the code is -> This is my car name demo

Variable Hoisting

Hoisting works with variables also , you can use the variables before they are declared.

var hoisting

The default initialization for var is undefined

console.log(num); // undefined
var num
num = 10
console.log(num)

the result would be similar if we declare the variables in the same line as well

console.log(num); // undefined
var num = 10
console.log(num)

if we forget to declare the initialization or forget to declare the variable we would be getting different error

console.log(num) //  Reference Error exception
num = 10 // initialization

let and const hoisting

variables declared with let and const are also hoisted but they are not initialized with a default value . if we do this we would be getting a common error like

console.log(num); // Reference Error exception 
let num = 6

Class Hoisting

Class hoisting is also like let and const variable hoisting when declared JavaScript would be having reference to initialize it . if they would be used before initialization we would be getting the similar error just like below

console.log(num) //  Reference Error exception
num = 10 // initialization