Introduction
Let vs Const vs Var is one of the oldest rivalries in JavaScript. This is a small article explaining the difference between all of them. Before going any further remember in JavaScript we have only function scope (the declarations are accessible only inside the declared block) and block scope (the declarations are accessible only inside the declared block). If anything is being declared outside all the blocks and functions, then it takes global scope.
var Keyword
var keyword takes function scope/global scope, which means a variable declared inside some other block is accessible anywhere in the code.
Example
if (true) {
var varVariable = "This is true from var";
}
console.log(varVariable);
Output:
This is true from var
We can access this varVariable outside the block as well. As well as you can redeclare the same variable again, this will overwrite the previously declared variable.
if (true) {
var varVariable = "This is true from var";
}
varVariable = "This is var variable outside the block";
console.log(varVariable);
Output:
This is var variable outside the block
Note:
variables created using var keyword are hoisted. If you are new to hoisting, then I would suggest you to see this video for better clarity.
let Keyword
The let keyword has block scope, which means it has scope only within the block it is declared and can not be accessed outside its block.
if (true) {
let letVariable = "This is true from let";
}
console.log(letVariable);
Output:
ReferenceError: letVariable is not defined
But within the block it is accessible.
if (true) {
let letVariable = "This is true from let";
console.log(letVariable);
}
Output:
This is true from let
Also if you mistakenly try to redeclare a let keyword variable error will be thrown, because let keyword variables can be declared only once.
if (true) {
let letVariable = "This is true from let";
let letVariable = "This is second declared true from let";
console.log(letVariable);
}
Output:
SyntaxError: Identifier 'letVariable' has already been declared
But you can re-assign values of letVariable.
if (true) {
let letVariable = "This is true from let";
letVariable = "This is re-assigned true from let";
console.log(letVariable);
}
Output:
This is re-assigned true from let
const Keyword
const keyword variables are very similar to let keyword, it has the same block scope. It doesn't allow you to redeclare variables. It also doesn't allow re-assigning new values. However, if you have declared an object with const keyword, Its properties can be changed.
const constVar = { name: "Kumar" };
constVar.name = "Indira";
console.log(constVar);
Output:
{ name: 'Indira' }
Conclusion
It is always advised to use const and let as best practices. cont keyword, when you won't or don't accidently wanna re-assign new values to your variable. Use let keyword when you want to re-assign values to your variable.
Top comments (0)