var vs let vs const ?

Var, let, and const are all used to declare variables. You can put all kinds of information on them. Strings, Int, Object, Array, Function. So what separates them? Which one is best? etc etc.

Var: A variable can be defined with a string, later on, reassigned to an integer, and later it could be assigned to anything else.

var name=’Harvey’;
console.log(‘name’,name); //name Harvey
name=10;//Reassign name
console.log(‘name’,name); //name 10
var name=’Mike’; //Redefine name
console.log(‘name,name); //name Mike

With var, we can reassign as well as redefine the same variable which we can’t do with let and const and this is actually bad because if you redefine a variable by mistake and overwrite it. It can cause hard to debug issues down the line.

Let: With let, we can reassign values but cannot redefine it and there is practically no reason to redefine values.

let name=’Harvey’;
console.log(‘name’,name); //name Harvey
name=10;//Reassign name
console.log(‘name’,name); //name 10
let name=’Mike’; //Redefine name not possible
console.log(‘name,name); //Error

Const: With const, we can neither reassign nor redefine values.

const name=’Harvey’;
console.log(‘name’,name); //name Harvey
name=10;//Reassign name not possible
const name=’Mike’; //Redefine name not possible

The whole point of a const is that its value is not changed so start using const by default and switch to let if you want to reassign values.

SCOPE

var, let and const are all function scoped meaning that they are specific to the function in which they are created and are not accessible outside the function.

let and const are block-scoped meaning they are bound to both function and code block(ex: for loop, if statement) while var is not. Thus they are accessible only inside the code block.

The following code will make things clear :

var fullName =’Bruce Wayne’;
if (fullName) {  
var firstName = fullName.split(‘ ‘)[0]  
console.log(firstName);//Bruce
}
console.log(firstName);//Bruce Accessible outside code block too
var fullName =’Bruce Wayne’;
if (fullName) {  
const/let firstName=fullName.split(‘ ‘)[0]  console.log(firstName);//Bruce
}
console.log(firstName);//FirstName is not defined

So follow this order if you start a project in JS: const(first), let if you want to reassign values and var never.

Hope I made it clear

ThankYou!!

© 2021 Asim Ansari | Software Engineer at Simpplr