What is Hoisting in javaScript ?
When javaScript compile your code variables declaration using var & function declarations moved to top of your code.
(moving means hoisted)
- If variable defined inside function or local block so it moves top of the them.
- If declared outside of function so move to top of the global scope.
So no matter anywhere you declare variable it will automatically be to top of the code, is called HOISTING.
Lets understand it by example —
In case b what happen variable value defined after console still not give reference error because what actually happen when compile code —
var firstName;
console.log(firstName);
firstName = “ Shivam ”
So it gives undefined (Variable declared but value not assigned )not a reference error.
So in Hoisting only variable declaration moves to the top not actual value;
What actually happen in hoisting —
sayHello(“Hello Sir !”)
function sayHello(message) { console.log(message) }Output- Hello Sir
is that your function and variable declarations are added to memory during the compile phase.
In the example above, because our function declaration was added to memory during the compile stage, we’re able to access and use it in our code above where it is typed.
Guess the output of this method —
So when we call method — printName() so what is output ?
a) Shivam Gupta
b) undefined
c) Saurabh
It will output undefined why ? because of hoisting. Looking tough to understand lets see what actually happen .
while compile this javascript code it will look like —
Cool ! If you like this article give a clap :)