let, const and var
JavaScript has three keywords for declaring variables:
varletconst
let and const were introduced in ES6.
1. var
var is the older way of declaring a variable.
var name = "Hemant";
console.log(name);
Reassignment
The value can be changed.
var age = 32;
age = 33;
Redeclaration
A var variable can be declared again in the same scope.
var name = "Hemant";
var name = "Rahul";
Scope
var is function scoped, not block scoped.
if (true) {
var age = 32;
}
console.log(age); // 32
2. let
let is used when the value of a variable may change.
let age = 32;
age = 33;
Redeclaration
A let variable cannot be redeclared in the same scope.
let age = 32;
// let age = 33; // Error
Scope
let is block scoped.
if (true) {
let age = 32;
}
console.log(age); // Error
3. const
const is used when a variable should not be reassigned.
const pi = 3.14;
Reassignment
A const variable cannot be reassigned.
const age = 32;
// age = 33; // Error
Redeclaration
A const variable cannot be redeclared in the same scope.
const name = "Hemant";
// const name = "Rahul"; // Error
Scope
const is block scoped.
if (true) {
const city = "Almora";
}
console.log(city); // Error