What is the difference between var and let in JavaScript?

We can declare a variable in javascript by using var keyword or let keyword all though their is difference between the variable declared with var and variable declared with let .

Below we come to know the major difference between var and let in javascript.

The key difference between let and var is that scope of a variable defined with let keyword is limited to the block in which it is declared while variable declared with var keyword has the global scope. So we can say that var is rather a keyword which defines a variable globally regardless of block scope.

The scope of let not only limited to the block in which it is defined but variable with let also do not get added with global window object even if it get declared outside of any block. But we can access variable with var from window object if it is defined globally.

Because of limited scope let variables are usually used when there is limited use of those variables such as in loops or inside the if conditions etc while var variable is used when value of variable need to be less change and used to accessed globally.

One more difference is that var can be redeclared to some other value while variable defined with let could not be redeclared, it will give error.

Below code will show the difference between var and let.

var x= "hey Javascript";  
var count= 5;  
if (count> 3) {  
   var x= "Hello Javascript";   
console.log(x) //Output: Say Hello Javascript  

let x= "hey Javascript";  
let count= 5;  
if (count> 3) {  
   let y= " Hello Javascript";   
   console.log(y) // Output: Hello Javascript  
console.log(y) // Compile error: y is not defined  

What is the difference between var and let in JavaScript?expoundsofttechsolution