Unlike other programming languages JS uses let, var, and const keywords for variable declaration.
Today we are going to see what is the significant differences between them.
var
Let and const came into the picture after ES6, before that people use only var for variable declaration. We can see the use of var by seeing the below example.
var a=10; //here a declared as a variable using var keyword
console.log(a);
Problems with var Unlike other languages, var is having function/global scope(what is a scope?? -> give a reading) and this problem sometimes leads to confusion.
{
var y=10;
}
console.log(y); //output->10 here the scope of var is global as it is not declared inside a function
But it is important to notice
function gun(){
var z=20;
}
console.log(z); //will throw an error because it is defined inside function and the scope will end there itself.
So as shown in the above example we can come to a conclusion that var variables first give importance to function scope than global scopes. If the variable is declared inside the function then it will not be available outside the function.
let and const
unlike var, let and const is having block scope and hence it works similar to other variable declaration types in the majority of programming languages.
let a=12;
{
let a=10;
}
console.log(a); //12
Interesting to notice-> If we use var in place of let
var a=12;
{
var a=10;
}
console.log(a) //10
Interesting no?? why it is giving 10 instead of 12?? Here the concept comes Hoisting. (We will see in the next blog) You can read about it
const acts like the same as let but only one difference we can't change it after initialization and we have to initialize const variable at the time of declaration only. Here are some examples
const a;
{
a=10;
}
console.log(a); // will throw an error as a is not initialized at the time of declaration.
If we want to assign another value it will throw an error.
const a=10;
a=12; //here it will throw type error
Interesting points to notice in const Array values or object properties can be changed but we can't reassign another array or object to it->
const arr1 = ["p", "s", "c", "a"];
arr1[2] = "n"; // possible
const obj={a:2,b:3};
obj.a=22; //possible
//but we will get an error
arr1=[]; //type error can't be reinitialize
obj={c:4,d:5} //type error can't be reinitialize
Summary var -> function/ global scope, can be reinitialize let -> block scope, can be reinitialize const -> block scope, can't be reinitialize