I often see JavaScript developers struggle to understand HOISTING in JavaScript. In this article let us try to understand the hoisting in simple words.
All JavaScript variables are hoisted to the top of the scope (function) in which they are defined. To understand it consider the following code snippet:
- var foo = "foo";
- console.log(foo);
The preceding code will print foo in the console. Simple, isn't it? Now let us proceed and add a function as shown in the following listing,
- var foo = "foo";
- console.log(foo);
-
-
- (function () {
- console.log(foo);
- }
- )();
Foo will be printed twice on the console. We saw that a variable defined outside a function scope or in global function scope can be used inside other functions. Let us proceed and modify the function as shown below.
- var foo = "foo";
- console.log(foo);
-
-
- (function () {
-
- console.log(foo);
- var foo = "zoo";
- }
- )();
To be surprised, now the second console statement will print the value undefined. Well, why it is happening? These are the following reasons for that:
- We have again declared foo inside the anonymous function.
- As we discussed earlier, JavaScript always hoists a variable declaration to the top of the scope. It only hoists the declaration, not the initialization.
Actually, the preceding anonymous function can be seen as in the following. The declaration has been moved to the top of the function scope, whereas the initialization is done where the variable is declared.
In the preceding function, we are trying to access the variable foo before it is initialized and that's the reason we are getting the undefined value printed. There are the following two types of scoping in JavaScript:
- Function scope
- Global scope
A variable is always hoisted to either the top of the function scope or global scope. When you use a var to declare a variable inside a function, then that variable is inside that specific function scope. When you declare a variable without using var, it is always in the global scope. I hope you now have a better understanding of hoisting in JavaScript.
You can also read an explanation on LET that is part of ES6 Derick Bailey blog.