An Overview : Hoisting in JavaScript

What is Hoisting ?

In Simple Word , Defining the declarations at the top of the scope before code execution is known as hoisting in JavaScript.

One of the advantage of hoisting is that we can call a function before they appear in the code.

someFunction(); 

function someFunction(){
    console.log("Hey !!!")
};

Important : JavaScript only hoists declarations, not initializations .


Variable Lifecycle

Variable declaration and initialization take place in the order described below :


var someVar ; // Delaration

someVar = "Javascript" ; // Initialzation / Assignment

console.log(someVar) ; // Usage

However, as JavaScript enables both declaration and initialization of variables simultaneously, this is the commonly used pattern :

var someVar = "React" ; // Delaration & Initialzation at same time


Hoisting with var

Hoisting with var keyword is somewhat different in comparison to let & const .

var someVariable  = 10;

console.log(a); // expected output 10
console.log(a); // expected output undefined

var someVariable  = 10;

In the above code , when we try to log the variable name which was declared and assigned later , it gives "undefined" as a result . This is because of hoisting , JavaScript first scan all the variables & functions and assigned the value of undefined to variable & block of code { } to function.


Hoisting with let & const

let & const are hoisted differently than var keyword


let someVariable = 25;

console.log(someVariable) // expected output 25

console.log(someVariable) // Reference error

let someVariable = 25;

In the var keyword, we expect the output of the log to be undefined. However, In let keyword variable declaration not allow us using undeclared variables, the interpreter throws a Reference error explicitly. This makes sure that we always declare our variable first.


Summary

Many developers are unaware of JavaScript's Hoisting behavior. Its significance is also overlooked by many developers. In addition, programmes may have bugs if a developer doesn't grasp hoisting (errors). Always declare all variables at the start of each scope to prevent issues. Thus, this is how JavaScript interprets the code, it is always a good rule.