Many of us has given Interview on Js or will be giving an interview in future, the most asked question is about Hoisting in js and how it works, I don't want you, people, to get stuck while explaining the Hoisting, In this blog, I will cover the concept in-depth so that you can Impress the Interviewer with knowledge of Hoisting ..get ready!!
Let's see the actual definition of Hoisting -
Hoisting in Javascript is the default behaviour of moving function and variables declarations to the top.
Many of us now will be confused by looking at the definition, It's okay I will explain this with examples.
Before moving further you must be familiar with the concept of Execution context and call stack !
Here is a quick recap from execution context that will help to understand Hoisting well In the execution context the variables are scanned and given the value as undefined, whereas the functions are scanned and made available.
Let's see an example
var x = 7;
console.log(x);
You might have guessed the output too easy that will be 7.
But what if I move the variable declaration to the top, Will it give me the value 7? let's see what will be the output.
console.log(x);
var x = 7;
//output - undefined
Here comes the weird stuff called Hoisting If I move the variable declaration to the top, It gives us undefined Why is that so?
In the execution context, as I have told at the starting of the blog that variables are scanned and made undefined in the creation phase, Let's visualize this.
As you can see in the creation phase the value of x is undefined, now when it comes to the second line of code and sees the value of x it gives the value back to x in the execution phase.
Now, let's look at how functions work in Hosting.
sum(4,5)
function sum(a,b){
console.log( a + b)
}
You will be amazed by the output Unlike a variable, the functions are scanned and made available, so even before declaring the function, we can call the function and It works perfectly!! Let's visualize this also.
Here in the creation phase the whole function is present itself. Now in the execution phase, the function gets invoke and perform the operations.
Last note to add If we pass a function as an arrow function or pass it to a variable, The execution context will see this as a variable and make It undefined. I hope you understood the concept, now next time the Interviewer asks What is hoisting, Explain them with these concepts.