JavaScript’s Basic Idea Of Hoisting
In JavaScript, hoisting is a behavior where a function or variable can be used before declaration.
The output of the program as mentioned above is undefined, but it runs. The program as mentioned earlier acts in the following ways:
Since the variable myName is just declared and has no value, it is given an undefined value.
Visit JavaScript Variables if you want to know more about variables.
The function and variable declarations are added to memory during the build phase, despite the fact that hoisting makes it appear as though the declaration has moved up in the programme hierarchy.
Variable Hoisting
When it comes to variables and constants, the keyword var is hoisted, but let and const do not permit hoisting.
Variable b is used previously to being declared in the case above. The program works, and output 10 is shown. As it operates, the program:
However, initializations are not hoisted in JavaScript.
The above program behaves as
In the build stage, only the declaration is copied to memory. As a result of the variable being printed without initialization, its value is undefined.
f a variable is used with the let, const keyword, that variable is not hoisted. For example,
Function Hoisting
A function can be called before declaring it. For example,
The function sayHi is called before it is declared in the previous code, and the output is displayed. Hoisting is to cause for this.
However, because only declarations are hoisted, an error happens when a function is used as an expression. the following;
Conclusion
Hoisting in JavaScript comes with a number of restrictions, so it’s usually advised to use strict mode or declare all your variables at the beginning of the file to prevent misunderstanding.