Hoisting in JS explained in 2 minutes!!

Rohan Gupta
2 min readFeb 16, 2021

When we declare a variable using the var keyword, the declaration of that variable is put into the memory component of the browser during compile time. That variable is hoisted in the memory. So, if we try to access that variable before its declaration, we won’t get an error.

var num = 123;
console.log(num);
//op - 123

This is pretty straightforward that the above code will give 123 as output.

console.log(num);
var num = 1234;
// op - undefined

Things get interesting when we run the above code, it will not throw an error unlike other programming languages and will print undefined to the console. This is known as hoisting.

Scope of Hoisted variable —

The hoisted variable is function scoped instead of block-scoped, for example, if we declare a variable in a for loop or if/else block we will still be able to access it outside its block like in the code below:

function fun1() {
console.log(num);
if(/*some truthy value*/){
var num = 10;
}
}
fun1();
// op - undefined

But if we try to access this variable outside the function, it will through a reference error like in the code below:

function fun1() {
if(/*some truthy value*/){
var num = 10;
}
}
fun1();
console.log(num);
// op - reference error

One thing to remember is that only declarations are hoisted which means we won’t be able to access the value of a variable before its initialization. That is the reason we get undefined as the output.

REFERENCES —

  1. https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
  2. https://youtu.be/Fnlnw8uY6jo

Connect with me on LinkedIn.

Do drop an 👏 if you liked this article.

--

--