Hoisting in Javascript
Deepa Chaurasia
Posted on July 6, 2022
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
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:
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.
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
Now let's see what happens if we do not declare var what happens
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.
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.
*Only Function declaration are hoisted ,not function expressions. *
It will throw error like this:
If you use let or const then it will throw error like this:
Hope it will help you guys:)
Posted on July 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 4, 2023