Skip to main content

JavaScript Variables Hoisting in Details

variable hoisting in JavaScript

Variable hoisting is a default behaviour in JavaScript where all variable declarations are moved to the top of the current scope (function scope or global scope) that the variable is defined within.

The typical JavaScript variable can be created in 2-stages : declaration and initialisation.

  • The declaration stage is where only variable reference is created, without any value. At this stage, if we try to access the variable value, we will get output undefined.

  • The initialisation stage is where the actual value is assigned to the variable.

Let’s see an example :

 ➤ Example :

    In this example, we can see the variable declaration stage, initialisation stage or both variable declaration & initialisation.

<script>
   var name; //Declaration
   name = 'Ankaj!’; //Initialisation
   var message = ‘Hello!’; //Declaration & Initialisation in one step
</script>



1.) Variable hoisting globally :

Let’s see an example of globally variable hoisting :

  • In this example, we can see in a normal scenario, when x is used before the declaration. In this case, it will give output 10 as excepted.

 ➤ Example 1 : Variable declaration before hoisting ;

<script>
   x=10; //Assign 10 to x;
   document.write(x); 
   var x; //Declare x
</script>

Let's take a look at how JavaScript interprets Example 1, how does it look after the hoisting process is finished. Javascript compiler change Example 1 to Example 2.

 ➤ Example 2 : Variable declaration after hoisting;

<script>
   var x; //Declare x, (Hoisted)
   x = 10; //Assign 10 to x
   document.write(x);
</script>

Example 2, Explanation :

In Example 2, we can see JavaScript hoisting behavior var x; is declared before the initialisation(x=10;). In this case, variable declarations are moved to the top.

Let’s see another example of variable hoisting :

 ➤ Example 3 :

<script>
   // ReferenceError: x is not defined
   console.log(x); 
</script>
  • At first in Example a, you may think that the sample code would throw a ReferenceError: on line 2 (console.log(name); because 'name' has not been declared yet.

 ➤ Example a : Variable declaration before hoisting;

<script>
   console.log(name); //undefined
    var name='Ankaj';
   console.log(name); //Ankaj
</script>

Let's take a look at how JavaScript interprets Example a, how does it look after the hoisting process is finished. Javascript compiler change Example a to Example b.

 ➤ Example b : Variable declaration after hoisting;

<script>
   var name; //Hoisted the declaration but not assignment
   console.log(name); //undefined
   name='Ankaj';
   console.log(name); //Ankaj
</script>

Example b, Explanation :

When the variable is hoisted, the declaration is moved to the top, but the initial value assignment remains in place, var name; is hoisted to the top of the scope, however the initial value assignment name = 'Ankaj'; is not affected.

2.) Variable hoisting locally :

 ➤ Example : Variable declaration before hoisting;

<script>
   var message="Document scope";
   function myMessage()
     {
       console.log(message); //undefined
       var message = 'Function scope';
       console.log(message); 
     }
     myMessage();
</script>

 ➤ Example : Variable declaration after hoisting;

<script>
   var message="Document scope";
   function myMessage()
     {
       var message; //This has been done by the javascript itself behind the scenes.
       console.log(message); //undefined
       message = 'Function scope';
       console.log(message); 
     }
     myMessage();
</script>

3.) Variable hoisting with block :

 ➤ Example : Variable declaration before hoisting;

<script>
    function display()
     {
       if(false)
        {
          var message = 'hello';
        }
        console.log(message); //undefined
     }
     display();
</script>

The variable message defined inside if block is visible to the outside block but within the function display() scope. This is because the JavaScript engine read the above code as following :

 ➤ Example : Variable declaration after hoisting;

<script>
    function display()
     {
       var message; //Hoisted the declaration but not assignment
       if(false)
        {
          message = 'hello';
        }
        console.log(message); //undefined but no reference error
     }
</script>

Javascript variables hoisting with var, let and const ?

Note : Variables and constants declared with let or const keyword are not hoisted.

Hoisting with var :

  • Variables declared with var are hoisted to the top of the enclosing function scope. If the variable is accessed before variable declaration, it evaluates to undefined.

 ➤ Example i : Variable hoisting with var;

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

In this example, name is accessed before declaration with var. In this situation the declaration is moved to the top.

Hoisting with let :

  • Variables declared with let are not hoisted.

 ➤ Example ii : Variable hoisting with let;

<script>
    console.log(name); //ReferenceError
    let name = "Ankaj";
</script>

Hoisting with const :

  • Variables declared with const are not hoisted.

 ➤ Example iii : Variable hoisting with const;

<script>
    console.log(name); //ReferenceError
    const name = "Ankaj";
</script>

JavaScript initialization are not Hoisted ?

  • The moving of var statements only applies to the declaration of a variable. If there's an initialization combined with the declaration, the initialization stays where it is, and declarations are moved to the top of the current scope.

JavaScript only hoists declarations not initializations, Let’s see an example :

 ➤ Example :

<script>
    console.log(name); //undefined
    var name = "Ankaj";
</script>

Comments

Popular Posts

Django static files not working when debug false || debug true

# Django static and media files not working when debug is false In this article you will learn how to fix problem of not loading static files and media in Django even the DEBUG is FALSE. This is the easiest and safest solution. # Problem: Django static and media files not working when debug is false  ➤ Code: settings.py DEBUG = False #True ALLOWED_HOSTS = [ '*' ] #Host name # Problem Fix: Let's see, How you can fix the problem of Django static and media files not working when DEBUB = False : 1.)First way: devserver in insecure mode If you still need to server static locally ( e.g. for testing without debug ) you can run devserver in insecure mode: python manage.py runserver --insecure --insecure: it means you can run serve

java program for student details using inheritance

# Java program to print student details using "single-level" inheritance In this section, You will learn how to print student details using single inheritance in java, with Scanner and without Scanner class. 1.) With " Scanner " class Let's try to create a simple example :   ➤ Example : student.java; import java.util.Scanner; class StudentDetails {    int roll_no ;    String name , cl ; //creating a function to take student details    void input () { Scanner sc = new Scanner ( System . in );   System . out . print ( "Ente

How to remove the date and .html from every blogger post url

#Remove date and .html from blogger post url A Common search term which every blogger search is How to Remove Date From Blogger Post URL or how do I remove date from blogger permalink? Follow the steps below and then date and .html will be removed from the URL of your blogger post. Step 1 : Login to your Blogger blog and select Theme / Template. Step 2 : Click on Edit HTML and paste the below code just above the </head> tag let's see code :   ➤ Code : mycode.js; Copy code <script type='text/javascript' > //<![CDATA[ // BloggerJS v0.3.1 var urlTotal,nextPageToken,postsDatePrefix=!1,accessOnly=!1,useApiV3=!1,apiKey="",blogId="",postsOrPages=["pages","posts"],jsonIndex=1,secondRequest=!0,feedPriority=0,amp="&"[0];function urlVal(){var e=window.location.pathname,t=e.length;return