Javascript: Var vs Let vs Const
Here are some of the differences between var, let and const keywords in JavaScript.
Table of contents
Var is the first keyword introduced to Javascript for declaring variables. This keyword is different from others and has unique properties and use cases. So before ES6 was introduced most people used the var keyword, but nowadays people stopped using this keyword because of these new keywords
ES6 Introduced 2 new keywords for declaring variables in Javascript.
Let: Accessible only Block level and can be reassigned.
Const: Accessible only Block level and can't be reassigned.
Introducing new keywords made var obsolete.
Differences
Var | Let | Const | |
Scope | Anywhere | Block | Block |
Reassign | Can be Reassigned | Can be Reassigned | Cannot be Reassigned |
Redeclaration | Supported | Not Supported | Not Supported |
Hoisting | Supported | Not Supported | Not Supported |
Initialize on Declaration | Not required | Not required | Required |
Code Examples
- Var Keyword
var name = "Prajwal Aradhya";
var counter = 3;
console.log(name); // Prajwal Aradhya
if (counter > 2) {
var name = "Aradhya, Prajwal";
}
console.log(name); // Aradhya, Prajwal
- Let Keyword
let name = "Prajwal Aradhya";
let age = 10;
if (age % 5 === 0) {
console.log("๐");
} else {
console.log("๐");
}
- Const Keyword
const title = "A good movie";
const rating = 5;
// Movie "A good movie" has 5 ๐ rating.
console.log(`Movie "${title}" has ${rating} ๐ rating.`);
ย