Hoisting in JavaScript: Simplified

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:

  1. var foo = "foo";  
  2. 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,
  1. var foo = "foo";  
  2. console.log(foo);  
  3.   
  4.   
  5. (function () {  
  6.     console.log(foo);  
  7. }  
  8. )();  
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.
  1. var foo = "foo";  
  2.     console.log(foo); // print foo  
  3.   
  4.   
  5.     (function () {  
  6.   
  7.         console.log(foo); // print undefined   
  8.         var foo = "zoo";  
  9.     }  
  10.     )();  
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: 
  1. We have again declared foo inside the anonymous function.

  2. 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.

function

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:

  1. Function scope
  2. 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.

Up Next
    Ebook Download
    View all
    Learn
    View all