WTF! Hoisting in Javascript 🏳️

Abhirup Datta
2 min readNov 30, 2020

--

Photo by Naveed Ahmed on Unsplash

* Hoisting is the behaviour of moving (hoisting) all the declarations at the top of the scope before code execution.

* It gives us an advantage that no matter where functions and variables are declared, they are moved to the top of the scope (local or global).

Hoisting for functions

Let’s see the output of the below code:

sum(10,20); 
function sum(a,b){
console.log(a+b);
}

The above code runs and prints out 30 because the function declaration is hoisted to the top during compile phase.So the compiler sees:

function sum(a,b){
console.log(a+b);
}
sum(10,20);

Function expressions are not hoisted

console.log(notHoisted);
notHoisted(10,20);
var notHoisted = function(a,b){
console.log(a+b);
}

The code fails and shows

undefined
Uncaught TypeError: notHoisted is not a function

This is because the compiler sees.

var notHoisted;
console.log(notHoisted);
notHoisted(10,20);
notHoisted = function(a,b){
console.log(a+b);
}

So notHoisted is not a function until line 4 is reached.

Hoisting for variables

Let’s see what happens when we declare a variable with var keyword

console.log(num);
var num; //declaration
num = 6; //initialization

The code prints undefined.This is because the compiler hosts and puts
var num on the top of the code (before the console log statement) .At that point num is declared but not initialized .Hence undefined is printed.

Let’s see what happens when var keyword is not used.

console.log(num);    //ReferenceError: num is not defined
num; //There is no hoisting since not declared with var
num = 6;

Using with let and const

Variables declared with let and const keywords are not hoisted.

console.log(num,a);
let num = 6;
const a = 10;

The above code fails and throws

ReferenceError: Cannot access 'num' before initialization

Update : 13/1/2021

Variable hoisting with if-else block

No matter the if condition pass or not pass,the declaration is always hosited.

There it is .The hoisting is quite annoying yet useful behaviour in Javascript and understanding it will help to mitigate the problems.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Abhirup Datta
Abhirup Datta

Written by Abhirup Datta

Frontend developer and startup enthusiast.

No responses yet

Write a response