var Vs let Vs const (JavaScript)


2 min read

let is used to declare variables now-a-days in javascript. On the other hand "var" is the old school way to declare variables. There are subtle differences between the two. Read on to find out more:

  • "var" has no block scope: What it means is that whenever we declare a variable using var in a block, it's scope is not limited by the block in which it is declared. It can be accessed anywhere in the code, regardless of where the block ends. The above fact holds true for all blocks such as if-else, for etc. except for the blocks which follows a function. That is, if a variable is declared using "var" inside a function, it's scope is limited to the block of the function.
    var a = 2}

console.log(a)  //2, the variable lives after the block
for(let i = 0; i<5; i++){
     var sum = 0;
     sum = sum + i;

console.log(sum);  //15, the variable lives after the block.

However, if we use let in place of var in both the above examples, reference error will occur.

  • Variables with same name within a scope can be declared using "var" any number of times. However, we'll get an error if we do that with let.
// This will not give any error.
var userName = "rajat"
var userName = "ron"
  • "var" variables can be declared below their use that is, it is possible to use a variable even before its declaration using "var".
number = 2;
var number;

However, the above code will give error if we "let" instead of "var".

  • When a programmer is sure that a variable will never change, he can make it a constant using the "const" keyword. Hence, it will give an error if someone tries to re-assign it a different value. Other than this very fact there is no difference between "const" and "let".

I write articles related to web development. Follow me here if you are learning the same.

If you love the article follow me on Twitter: @therajatg

If you are the Linkedin type, let's connect:

Have an awesome day ahead ๐Ÿ˜€!