Hoisting in Javascript
Nikita Gore
Associate at Cognizant | Frontend developer | AEM Frontend Developer | React JS | Vanilla JS | jQuery
What is Hoisting?
Hoisting is a built-in feature of JavaScript that allows you to use functions or variables before declaring them. However, does this mean you can use the value assigned to a variable before the assignment? NO!
For variables, only the declaration and the default value assigned at the time of memory allocation ("undefined") get hoisted, not the assigned value.
Example:
This will result in "undefined".
The key point here is that it will not throw an error when you try to access 'a' before declaring it. The code will execute without throwing an error because 'a' gets hoisted with the default value "undefined". This behavior is specific to variables declared with "var".
For 'let' and 'const', hoisting works differently.
This will result in a reference error: "Cannot access 'a' before initialization". From the error message, we can see that 'a' gets initialized somewhere. This means the variable gets hoisted but not with a default value, unlike 'var' variables.
If 'let' variables didn't get hoisted, it would have given "Uncaught ReferenceError: a is not defined". This indicates that variables defined with 'let' or 'const' get hoisted but not with a default value. This is because 'let' and 'const' remain in the temporal dead zone until a value is assigned, making them inaccessible until the code reaches their assignment.
领英推荐
For functions, the function definition gets stored at the time of memory allocation, allowing the function to be invoked before its declaration. Only function declarations get hoisted, not function expressions.
Example:
This will execute successfully and console "Hello World!!!".
However,
OR
will give an error because function expressions are treated as variables.
Understanding hoisting is essential for mastering JavaScript. By knowing how hoisting works, you can avoid common errors and write cleaner, more efficient code.