Hoisting in JavaScript

What is hoisting in JavaScript?

So, Basically Hoisting refers to an phenomena that refers to moving declarations of variables and functions to the top of the scope(usually Global Scope).

Hoisting is JavaScript's default behavior of moving declarations to the top.

Since we have multiple ways to create a variable in Javacript:

  • Var

  • Let

  • Const

Var

Now the variables created using var keyword are hoisted in global scope,and are assigned undefined in the Window object, of Global scope.So if we would like to access this variable of type var before initialization we undefined.

Let

The variables created using let are hoisted as well but memory space other than window object of Global Scope , If we try to access the variables of type Let we get ReferenceError due to Temporal Dead Zone.

Reference Error

RefernceError is caused when a variable when declared Fails to map it's value due to Temporal Dead Zone.

Temporal Dead Zone

The time period between hoisting of a variable and it's first use in the program is called Temporal Dead Zone, in case of let & Const.

Const

The variables assigned with this keyword are generally Constant throughout the program meaning that they can't change their value during program run.

Eventhough Const is hoisted we get syntaxerror due to the javascript syntax forces us to initialize the const value when declared at same time.

Function expressions and Class Expressions aren't hoisted in Javascript