DEV Community 👩‍💻👨‍💻

Deepa Chaurasia
Deepa Chaurasia

Posted on

Hoisting in Javascript

Hoisting gives higher specificity to javascript declarations.Thus,it makes the computer read and process declaration first before analyzing other code in program

So hoisting doesn't mean javascript rearranges or move code above one another.

Let's say

Image description

In this case we are using the name before it's declaration,however because we are using 'let' keyword here it is throwing "Uncaught Reference Error " to us.

Variables declared with let and const are hoisted but not initialized with default value

Accessing let or const before it's declared gives following error:

Image description

So one thing to be noticed here is, this error message is telling that variable is initialized somewhere.

Variable Hoisting with var

When interpreter hoists a variable declared with var ,it initialize it's value to undefined ,unlike let or const.

Image description

Remember console.log(name) outputs undefined, beacause name is hoisted and given a default value (i.e undefined),not because variable is never declared.

Using Undeclared variable will throw the Reference Error
Like this

Image description

Now let's see what happens if we do not declare var what happens

Image description

Assigning a variable that's not defined valid actually.

Strange Isn't it??

Javascript let us access variable before they're declared.This behaviour is an unusual part of javascript .So it i adviced not to do this.

The Temporal Dead Zone

So why we get reference error when we try to access let or const before it's declaration??

This is because of Temporal Dead Zone.

The TDZ starts at the begining of variables enclosing scope and ends when it is declared.

Accessing variable in TDZ throws an error.

Image description

In case of let or const , it throws Reference Error in TDZ
However in case of var it assign it to undefined

Functional Hoisting

Not only variables but function declarations also get hoisted in javascript.

Functional hoisting allow us to call function before it is declared or defined.

Image description

*Only Function declaration are hoisted ,not function expressions. *

Image description

It will throw error like this:

Image description

If you use let or const then it will throw error like this:
Image description

Image description

Hope it will help you guys:)

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.