Hoisting in javascript

Rajan Lagah
2 min readNov 7, 2021

--

In js we can use variables or functions before they are declared.

console.log(a);
var a = 2;

This will not through any error and the output of the above code is

undefined

Why is that ?

Js run code in 2 steps.

  1. Memory allocation
  2. Code execution

In memory allocation js will scan the code and take variables and function and store them in memory as key value pare.

For example to run above code js will make map which contain all the variable which in this case is ‘a’

a:undefined
// for function js will store function definition
// someFunction: function(number){
// ..function definition
// }

Now in step 2 code execution phase it will run 1 line at time starting from 1st line.

console.log(a) // <--- 1st line

From memory allocation step we can see that value of a is mapped to undefined so the output will be ‘undefined’

at line 2 js will set value of a to 2

var a = 2; // At this step value of a in memory will be 2

But

console.log(a);
let a = 2;

This code will give error. That is because js Declare and Initialise ‘var’ during compile time but later to remove the confusion and increase code quality ‘let’ and ‘const’ only declare variables during compile time and initialisation is done during code execution. So ‘let’ and ‘const’ are declare but are not defined till the code execution line reaches the line where variable is assigned.

Conclusion

Modern JS provide us with ‘const’ and ‘let’ keywords to define variables we should use them where ever possible instead of ‘var’ to escape the hoisting confusion.

--

--

Rajan Lagah
Rajan Lagah

Written by Rajan Lagah

React expert and Deep learning beginner.

Responses (1)