Maybe you’ve heard about hoisting before but you don’t really understand what it means or rather how it works in JavaScript, in this article, I am going to explain in details about what it is, when you can use it and why you might want to use it.
Hoisting in JavaScript allow us to access both functions and variables even before they are created.
The 2 types of hoisting in JavaScript include:
- Function Hoisting
- Variable Hoisting
FUNCTION HOISTING
It’s a way of accessing a function declaration even before they get’s created. Anytime you declare a function, what JavaScript does is that, it takes your function and place them at the top level of your code and you can access it anywhere within your program. For instance:
myName();
function myName() {
console.log("victor");
}
The program works because JavaScript compiler will took all of my function declarations and move them to the top of the file so that they’re all available before I use them.
Because of hoisting, you can technically run a function before it exists.
VARIABLE HOISTING
This allow us to access a variable declaration before they’re initialised. For instance:
console.log(myName);
var myName = "victor";
We get undefined not Reference Error simply because JavaScript compiler will hoist the variable declarations but it will not actually hoist the setting of the values.
So what JavaScript does is it says before everything runs, I am going to make my variables and then I’m just going to go ahead and update them. One important thing to note here is that, let and const variables cannot be hoisted, they’ll not be initialised to undefined instead you’ll get a Reference Error.
I hope this article has been helpful to you. Don’t forget to give me a clap 👏 and follow me on twitter , facebook and youtube.