DEV Community

Limbareddy
Limbareddy

Posted on

Scope and usage of let , var & const keywords

for changing of values of var

var name =" jai";
var name = "ram" ;
console.log(name)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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) 

Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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());

Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)