Skip to main content

Difference between var, let and const

   var, let and const in Javascript

       Variable can be declared in three ways:
  1. var
  2. let
  3. const

var variables are function-wide scoped. Let's understand this with an example,
      var x = 5;    // variable declared with "var"         console.log(x);  // x will be 5
 console.log(x); // even here, x will be 5 

        So in the last example we can see variable "x" is available outside the "if" block, that means the scope of variable with "var" is not block scope.

let see with another example,

1.  function helloWorld(){      var x = 5;      
2.     function abc(){            
3.        console.log(x);      // even x will be 5      
4.     }      
5.     abc();      
6.     console.log(x);  // x will be 5
7. }
8. helloWorld();
       So in this example, we can see the variable "x" is available throughout the function in which it is declared.

One of the famous example/question discussed in the interviews is following

1.       for(var i=0;i<5;i++){
2.                console.log(i);
3.       }
4.       console.log(i)
Now, what you think the value we will get out of console.log(i) in line 2.

      Yes you guys are correct, we will get value printed 0,1,2,3,4 (obviously without comma), and we will get "5" from the console.log(i) in line 4, as "for" loop ends when the "i" reaches value 5 and doesn't match the criteria i<5, so when it comes out of "for" loop we will have i value 5.

NOTE: "let" and "const" keywords were introduced in ES2015 or ECMAS-6, before this variables were used to be declared only with "var".

Now let see the same example but with "i" declared with "let" keyword,

1.       for(let i=0;i<5;i++){
2.                console.log(i);
3.       }
4.       console.log(i)

        In this example, we will get values printed 0,1,2,3,4 from line 2, but we will get error from line 4,saying 

>Uncaught ReferenceError: i is not defined at <anonymous>

        this is due to the fact that variable declared with let keyword has block scope, so in the example above example when "i" comes out of "for" loop block, there is no existence of "i", and we get error saying i is not defined.

  lets see with var and let both in an example,

1.        var i = 10;
2.        for(let i = 0; i < 5; i++) {
3.             console.log(i)
4.        }
5.        console.log(i)

        So in this case, we will get 0 to 4 from line 3, as expected and here from line 5, we will not get error but 10 value as variable "i" is there in the memory with value 10 due to it's declaration with "var" keyword in line 1, giving variable "x" a functional level of scope.

       Now similar to let keyword, variable declared with const has block level of scope, but the value cannot be changed.

      const statement values can be assigned once and they cannot be reassigned. The scope of const statement works similar to let statements.

   e.g.      const  PI = 3.14;

    As per usual, naming standards dictated that we declare the const variable in capital letters. const PI = 3.14 will work the same way as the code given above.

 let's see what happen when we try to reassign a const variable.

1.     const x = 5;
2.     x = 10;          // here we will get error saying "Uncaught                    TypeError: Assignment to constant variable."

however, we can modify the value of array or object declared with const, but we can not reassign a value.


1.     const jsFramework = ["React","Vue"];
2.     jsFramework.push("Angular")   // No error
3.     console.log(jsFramework) // ["React", "Vue", "Angular"]

       So till now we have seen,

1. Variable with "var" keyword has functional level of scope and values can be  reassigned.

2. Variable with "let" keyword has block level of scope and values can be reassigned.

3. Variable with "const" keyword has block level of scope and values cannot be  reassigned.

      Now let's do some deeper analysis of var , let and const

      The JavaScript variables statement is used to declare a variable and, optionally, we can initialize the value of that variable.

var x;       // this is declaration
var x =10;    // declared and initialize

Example: var a =10;

Variable declarations are processed before the execution of the code.Something that we will learn in hoisting article.

The scope of a JavaScript variable declared with var is its current execution context.

The let statement allows you to create a variable with the scope limited to the block on which it is used.
    Also you cannot redeclare same variable with "let". e.g.

1.      function abc(){
2.        let a =10;
3.        let a =20; //throws syntax error "Identifier 'a' has already been declared"
4.        console.log(a);
5.      }

but with "var" we won't get any error.
1.     function abc(){2.        var a =10;
3.        var a =20;
4.        console.log(a);  //output 20
5.     }

with const we can't do the same(we have seen before).

Thank you.



  1. This really helped me to understand the scoping of variables in js.

  2. Content is very easy to understand. It is very helpful


Post a comment

Popular Posts

Come Closure in Javascript

What is a closure? If we want to derive a definition,we can say, A closure is a feature of Javascript where inner function has access to the outer (enclosing) function’s variables—scope chain. This scope chains means inner function has: access to its own scope (variables defined between its curly brackets and its parameters), access to the outer function’s variables and parameters,  access to the global variables. Now we will look into it in detail. Consider following example var globalVar = "xyz"; function outerFunc(outerArg) { var outerVar = 'Alex'; function innerFunc(innerArg) { var innerVar = 'Chris'; console.log("globalVar = " + globalVar); console.log("outerArg = " + outerArg); console.log("innerArg = " + innerArg); console.log("outerVar = " + outerVar); console.log("innerVar = " + innerVar); } innerFunc(456); } outerFunc(12

Javascript Hoisting Interview Question and Answers - 5

In this post,I have tried to cover all the types of possible interview questions and answers on hoisting. If you are not familiar with the hoisting, I would highly recommend you to go to my post on hoisting . Once you are comfortable with the topic, you can attempt these questions. Understanding the type of question will help you to answer. I have provided the hint after each question. All the answers are given at the end of the post. //Question 1 console.log('bar:', bar) bar = 15 var foo = 1 console.log(foo, bar) var bar Hint : Basics of hoisting //Question 2 var foo = 5 console.log('foo:', foo) var foo; var bar = 10; var bar; console.log('bar:', bar) var baz = 10 var baz = 12 console.log('baz:', baz) Hint : Basics of hoisting     //Question 3 function foo() { function bar() { return 5 } return bar() function bar() { return 10 } } console.log(foo()); Hi

Javascript Closure Interview Questions and Answers - 6

Here in the post, I have posted all the possible interview questions and answers on closure. If you are not familiar with the closure , I would highly recommend you to go to my post on   closure . Once you are comfortable with the topic, you can attempt these questions. All the answers are given at the end of the post. //Question 1 function foo() { var a = 5 function bar() { console.log(a) } return bar; } var baz = foo() baz()   // Question 2 function outer(a) { var b = 2 function inner() { var c = 5 console.log(a * b * c) } return inner; } var multiply = outer(5) multiply() // Question 3 const arr = [10, 20, 30, 40, 50] for (var i = 0; i < arr.length; i++) { setTimeout(function() { console.log('Index: ' + i + ', element: ' + arr[i]) }, 1000) } // Question 4 for (var i = 0; i < 5; i++) { setTimeout(function(i) { return function() {