Hoisting in JavaScript
Hoisting is the behavior of allocating memory to the variables or function declaration before code execution.
Its like move up your declare variable & Functions on your code. Hoisting can only apply for var or function keyword only for the variable default value is undefine and in function all block are allotted
Let’s play with ho🧸😎
In this example we try to access sayHello function before declaration but in this function we also try to use myName variable before there initialization as we know the variable default value is undefine so the out put will be
Output
Before Declaration
Hello ~ undefine
After Declaration
Hello ~ Gourav
What will be the Output 🧐
If you guess Gourav then congratulation you successfully made a mistake Ha Ha Ha… just kidding the output will be “Gourav Bhati”
Explanation
on the time of Hoisting every Piece of code that are start with function or var keyword will be checked in the case of function compiler check by Following
Step 1: Oh there is a function sayHello let’s allocate memory to it.
Step 2: on the time of Invocation of sayHello function again Hoisting happen.
Step 3: there is a function sayMyName (output : “Gourav”) lets allocate memory
Step 4: return statement not run because Hoisting is happening not execution then compiler check OOOH sayMyName function comes again lets replace it with old one then in memory sayMyName replace (output : “Gourav Bhati”);
Thanks for Reading this. Feel free to share any any issue /suggestion / query