The difference between var and let in JavaScript is block scope.
var
When a var is declared outside a block scope, and then re declared inside a block after the first declaration. The value of the var gets changed after the block scope is over.
//first declaration of var x
var x=10;
{
//second declaration of var x
var x=5;
alert(x); //prints 5
}
alert(x); //prints 5
let
However by using let keyword to declare a variable. the value of the variable doesn't get changed by the subsequent re declaration inside the block.
//first declaration of let var y
let y=15;
{
//second declaration of let var y
let y=90;
alert(y); //prints 90
}
alert(y); //prints 15
Top comments (0)