What is hoisting?
In simple words, hoisting is using variable and function before they are declared. Meaning variables and function declarations moved to the top of their scope before any other code execution, no matter where they are declared. This doesn't mean literally moving your code to top but, the compilers put the declaration into the memory first in the compile phase. The declarations are processed before any other code executed.
In the above example, when we do
console.log(name)at first, we get
nameis not declared previously. But when we check,
console.log(typeof name)we get
undefinedas output. It is because undeclared variables are assigned
undefinedat the time of execution. The
Here, we have used the variable
firstNamebefore it is declared. And
undefined. This doesn't give
ReferenceError. When we do
console.log(firstName)for the very first time. Initializations are not hoisted.
Similarly, function declarations are moved to the top means they are executed before any other code in the program. Check below code snippet.
It works perfectly fine as if the function
getName()is defined first and then called. This because the declaration is moved to the top. Below is how the compiler reads through the above code.
ES5 - strict mode
When we are using
firstNamewithout declaring, we get an error. Read more about strict mode here.
ES6 - let and const
const does not support hoisting. Let's see it n practice.
We get an error when using
constbefore the declaration. Learn more about let and const in the below article.
Understanding let and const.
Kamlesh Chavan ・ May 1 '20 ・ 3 min read
Let us recollect things we learned up above.
- Only declarations are hoisted, not the initializations.
- Using strict mode helps us prevent the use of a variable before the declaration.
constdoes not support hoisting.
Thank you for reading. 🎉
Top comments (0)