Javascript Hoisting : Variable Hoisting

Hoisting is Javascript’s default behavior of moving declarations to top of the file.

There are two types of Hoisting is there:

  1. Variable Hoisting
  2. Function Hoisting

Let’s first understand Variable hoisting with examples:

  1. Variable Hoisting: In this kind of Hoisting, Variables can be used before its declared. In other words, If you have declared variable at end of the file, but used at the beginning or middle of the file. Javascript moves declaration of variables to the top of the file.

 


a=1;

console.log("Variable a is hoisted at the beginning so this will print the value of a :->"+a);

var a; 

// Output would be: Variable a is hoisted at the beginning so this will print the value of a :->1

But be cautious, If you initiate the value of variable at the bottom of page and try to use at beginning or middle of code that it will give undefined as output.


console.log("Hoisting won't work here. Hence, a is :->"+a);

var a = 1; 

// Output would be: Hoisting won't work here. Hence, a is :-> undefined

 

Same way, Functions are being hoisted too. That we will learn in the next article.

 

Please let us know your feedback in comments. We will be more than happy to help to solve your doubts.

 

 

One comment

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.