DEV Community

sanjeev
sanjeev

Posted on

javascript variable declaration: var vs let vs const

We have 3 different ways to declare variables in java script

  1. var - Variables declared with var keyword are function scoped. What do I mean by that ? let's take an example -
    
    function sayHello(){
      for(var i=0;i<4;i++){
        console.log(i);
      }
      // As var is function scoped, i is available outside for loop.
      console.log(i); // This prints 4.
    }
    sayHello();
    
    
    Here, i is declared with var keyword in a for loop ( block ) and it is incremented util i < 4. When i becomes 4, the for loop ends and the last console.log(i) is executed. Output
    
    0
    1
    2
    3
    4
    
    
    Because of the var keyword, i is function scoped hence i is available outside the for loop as well and last console.log() prints 4.
  2. let - This is part of ES6 and addresses the problem related to var keyword. Variables declared with let keyword are block scoped. Let's consider the previous code with let
    
    function sayHello(){
      for(let i=0;i<4;i++){
        console.log(i);
      }
      // let is block scoped hence i is only visible inside for block.
      console.log(i); // This line will throw an error.
    }
    sayHello();
    
    
    Because i is declared with let, i is visible inside the for loop only and the last console.log() will throw an error ReferenceError: i is not defined Output
    
    0
    1
    2
    3
    Uncaught ReferenceError: i is not defined
        at sayHello (:6:15)
        at :8:1
    
    
  3. const - const keyword is used to define constants in java scripts and are block scoped. e.g.
    
    function sayHello(){
        const i = 1;
        console.log(i);// This prints 1
        i = 2;  // i is declared as constant hence this line will throw an error.
    }
    sayHello();
    
    
    if we try to reassign i with a different value within the same block then java script engine will throw an error TypeError: Assignment to constant variable Output
    
    1
    Uncaught TypeError: Assignment to constant variable.
        at sayHello (:4:4)
        at :6:1
    
    

Conclusion: With var keyword we may get unexpected output, so if the value of a variable is not expected to change then const keyword should be preferred else use let keyword to define variables.

Cheers!

Top comments (0)