DEV Community

Ashok Naik
Ashok Naik

Posted on • Updated on

Understanding let vs var vs constant in Javascript

All Javascript applications need to work with information in order to store information we make use of variables that are declared using var, let, const keywords.

The major difference between the variable declared as var and the variables declared as let and const are var creates a function scoped variable whereas let and const create blocked scoped variables.

What is function scoped variable ?

A function scoped variable is available anywhere declare inside the function

Note: if a var variable is not inside a function then it is globally scoped

What is block scoped variable ?

A block-scoped variable is only available inside the block it is declared in i.e if, while block

if(true) {
   var  var_variable = "This is a variable declared with var keyword"
}
 console.log(var_variable) 
 //Output: "This is a variable declared with var keyword"
if(true) {
   let  let_variable = "This is a variable declared with let keyword"
}
 console.log(let_variable) 

 //Output: Uncaught ReferenceError: let_variable is not defined

Enter fullscreen mode Exit fullscreen mode

Another difference is the variable declare with var keyword can be completely redefined but let variable cannot be redefined

var  var_variable = "This is a variable declared with var keyword"

var  var_variable = "var variable is redefined"

console.log(var_variable) 

 //Output: "var variable is redefined"

 let  let_variable = "This is a variable declared with let keyword";

 let  let_variable = "let variable is redefined" 

 console.log(let_variable)

 //Output: Uncaught SyntaxError: Identifier 'let_variable' has already been declared

Enter fullscreen mode Exit fullscreen mode

A variable declared with var can be used before it declared but in case of let or const it cannot be used.

Note: if a variable is declared using const keyword it cannot be reassigned

The properties of objects declared with const keyword can be
reassigned

const userDetails = { id:121 };

userDetails.id = 125

console.log(userDetails) 

Enter fullscreen mode Exit fullscreen mode

In the above example, the object userDetails is declared using the const keyword and its property id is reassigned.

Looking at all the above differences it usually recommended to use the let and const keyword over the var keyword.

That's All folks, Thank you.

Top comments (0)