What is Hoisting in JavaScript?

Shruti SinghShruti Singh
2 min read

So as we know JavaScript is synchronous by default i.e. JS run line by line. For example, observe the code below and tell the output.

function sum(a , b){
  return a + b;
}
console.log(sum(5 , 5))

//Output => 10

How about we declare a variable at last and try to send it as an argument in the sum function? What do you think will be the output?

function sum(a , b){
  return a + b;
}
console.log(sum(a , 5))

let a = 10;

We will get a Reference error. That's because we are trying to access the variable's value before it has been declared and initialized.

Okay now let me confuse you. What will be the output of the following code? Will it throw an error or not?

console.log(sum(5 , 5))
function sum(a,b){
    return (a + b);
}
//Output => 10

Yes, it will give us the output without throwing an error. This is where the concept of Hoisting comes into play.

Definition of Hoisting

Hoisting is a behaviour in JS where JS takes all the function and variable declarations at the top which makes it easy for us to access them before they are declared.

Function declarations are fully hoisted, meaning both the declaration and the function definition are moved to the top of the scope.

// Function Declaration
function greet(name) {
  console.log("Hello, " + name + "!");
}
greet('Developers')

Hoisting with Arrow functions

Remember arrow functions are not hoisted and that's because arrow functions are defined as a variable and variables never get hoisted.

const SumArrowFn = (a , b) => {
    return a + b;
}
console.log(SumArrowFn( 10 , 90 ))
//Output => 100

Hoisting of Variables

There is a difference in Hoisting behaviour between variables declared with var and those declared with let or const.

var : Variables declared with var are hoisted but initialized with undefined

let & const : Variables declared with let and const are hoisted but they remain in a "Temporal dead zone" until the actual declaration statement is encountered.

Temporal dead zone: This is a concept in JavaScript that refers to the period between the start of the scope where a variable is declared and the point where the variable is formally declared in the code. During this period, trying to access the variable results in a ReferenceError.

NOTE: Only the declarations are hoisted, not initializations. 👇This is what I mean.

console.log(sum(5,5))
console.log(x)//Uncaught ReferenceError: Cannot access 'x' before initialization
let x = 20; // Declarationsand Initializations
console.log(x)
function sum(a,b){
    x = 10;
    return (a + b);
}
0
Subscribe to my newsletter

Read articles from Shruti Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shruti Singh
Shruti Singh