It allows us to call functions before even writing them in our code.
Let us understand what exactly this is:
The following is the sequence in which variable declaration and initalisation occurs.
Declaration –> Initialisation/Assignment –> Usage
// Variable lifecycle let a; // Declaration a = 100; // Assignment console.log(a); // Usage
let a = 100;
Note: There’s a difference between ReferenceError and undefined error. An undefined error occurs when we have a variable which is either not defined or explicitly defined as type undefined. ReferenceError is thrown when trying to access a previously undeclared variable.
When we talk about ES5,the variable that comes into our minds is var. Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works:
Explanation: In the above code we tried to console the variable name which was declared and assigned later then using it,the compiler gives us undefined which we didn’t expected as we should have got ReferenceError as we were trying to use name variable even before declaring it.
But the interpreter sees this differently,the above code is seen like this:
Function scoped variable
Let’s look at how function scoped variables are hoisted.
There is no difference here as when compared to the code where we declared the variable globally, we get undefined as the code seen by the interpreter is:
In order to avoid this pitfall,we can make sure to declare and assign the variable at the same time,before using it. Something like this:
We know that variables declared with let keywords are block scoped not function scoped and hence it is not any kind of problem when it comes to hoisting.
Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first.
const behaves similar to let when it comes to hoisting.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.