for changing of values of var
var name =" jai";
var name = "ram" ;
console.log(name)
This console prints the value of ram , var overrides the value of name. This causes problem while debugging the code and increases the ambiguity of code .
For changing values of let
let name =" jai";
let name = "ram" ;
console.log(name)
We can see error that identifier name has been already taken , so let keyword not allowing reinitialization of identifier name , we need to use different names for the let keywords.
For changing values of const
const name ="jai";
const name =" ram";
console.log(name)
This console shows error that name has already assigned .
**So its better to use const for variables
let for if there is any changing of values
var is least prioritized **
For usage of var in scope
var fun ;
for (var i = 0; i < 3; i++) {
if(i ==2){ fun =() =>{
return i; }
}
}
console.log(fun());
when var is declared it is considered as global variable . The above console returns the value of 3 , because as the for loop iteration changes the i value by increment , so var i takes i value and returns as 3 .
For usage of let in scope
let fun ;
for (let i = 0; i < 3; i++) {
if(i ==2){ fun =() =>{
return i; }
}
}
console.log(fun());
Let is considered as block variable (within in the scope )
From the above code it returns the value of i as 2 ;
logically this result was correct .
From above Global scope of two keywords we see they were returning variables with different outputs
let keyword update was came in ES6 , we need to use let instead of var because of let keyword scope , updating values ,
So Finally
## const >>> let >>> var
Top comments (0)