What is Hoisting in JavaScript?
How about understanding it via example?
var name = "John Doe"
console.log(name)
As you already know this will print John Doe on your console. Nothing weird is going on here.
How about the following code?
name = "John Doe"
console.log(name)
var name;
Again this will print John Doe on your console. Is it weird? umm, you decide ๐ . I will explain why is it happening
Before running our program JavaScript actually moves all our variable declarations and function declarations to the top of the current scope. This is known as hoisting. Due to this code in the second snippet is working fine rather than throwing an error.
Hoisting is nothing but a feature of JavaScript where all the declarations of variables and functions are moved to the top of the current scope.
Let's have a look at another code snippet.
var name;
console.log(name);
name="John Doe"
What do you think it will serve on your plate?
If your answer is again John Doe then I am sorry to say it is wrong.
Why?
As I said Hoisting moves function and variable declarations only to the top of the current scope, not the Initializations. In the third code snippet, we have used the variable before its initialization that's why it will say undefined.
Let's have a look at functions now.
function greet(){
console.log("Have a good day!");
}
greet();
Do you know what is going to be the output? Yes, it will be Have a good day! because we have correctly defined the function first and then we've called it so no problem.
Here is my question to you now. What will happen if we move the function call before the function declaration?
- Let's see
greet();
function greet(){
console.log("Have a good day!");
}
This will work fine again. Do you already know why now? If not, let's see what happens to this code. When you run the above code the hoisting behavior will take the function declaration to the top and after that, our second snippet code will look exactly the same as the first function code snippet.
How about Function Expressions?
greet();
var greet = function(){
console.log("Have a good day!");
}
The above code will not work. Let's see why
Before the execution of the above code, the declaration of the function expression will move to the top but the initialization will stay down there after the function call. The above code will look something like this
var greet;
greet();
greet = function(){
console.log("Have a good day!");
}
Conclusion
- Hoisting allows us to call functions in our code before they appear in actual code, we can consider this as a benefit of hoisting.
If you want to get rid of this weird behavior of hoisting you should avoid using var and opt for let or const. I hope you learned something new today ๐ .
Thanks for reading this blog. if you find it helpful in any way kindly show some love โฅ๏ธ. Keep learning happy coding :)