Let's Explore Hoisting in Javascript, in less than Five Minutes

Let's Explore Hoisting in Javascript, in less than Five Minutes

I will explain the concept as I understand it or what comes to my mind when I hear the term hoisting. I will try to make this as simpler as possible.

ok. let's begin.

The term Hoisting is one of the most fascinating terms of js.

The word ‘hoisting’ means lifting something up. In js declarations are hoisted. ex: variables and functions.

Javascript hoists ( lift up ) declarations before the function call. That's why we can call a function before declaring it. If it's an arrow function then there is some differentiation.

which brings me to the next point,

functional-scoped variables and block-scoped variables are hoisted differently. 

For example,

  var a = 10;                

In this single line, js have done three tasks.


var a; //(a                 )

a = undefined; // ( assign undefined to the variable ) 

a = 10; ( assign 10 to the variable )        

Now, if we write this and run


console.log(a);

var a = 10;

//output : 10        

bit weird! because of hoisting, js hoisted those three particular tasks ( declaration, assign undefined, and assign 10 ) before the function call. In this case console.log (a).

  js rearranged the code like this,


var a = 10;

console.log(a);        

  Global scoped variables and normal function declaration are hoisted this way. But if we rewrite the code, this time as  let/const variable like this,


console.log(a);

let a = 10;

//output: a is not defined        

Interesting…. js should have hoisted the variable before the functional call, then why is it giving the error?

 js hoisted the let variable, yes, but differently. As we have discussed before, when we write this,


let a = 10;        

  three actions happen. declaration, assign undefined, and assign 10. 


let a;

a = undefined;

a = 10;        

 for block-scoped variables, javascript only hoists these two tasks. rather than three of them. like this,


let a;

a = undefined;                

   what I meant is, js sees the code as


let a;

a = undefined;

console.log(a);

a = 10;        

      That's why it was giving the error. 

So, if I summarize the concept,

  • js hoists all declarations, before the function call
  • for the global variable (var ) and normal function it hoists the declaration and the actual value. ( for function, it hoists the whole function body )
  • for the block-scoped variable ( let / const ) and arrow function ( declared with let/const) it only hoists the declaration, not the actual data.

To view or add a comment, sign in

More articles by Taiyeb Nirjhor

Others also viewed

Explore content categories