let & const keywords were introduced in ES6 (2015).var existed since Javascript's inception
const:
Identifiers declared with const cannot be re-assigned
const name = "Hassan"
name = "Arafat"; // This will give an error
let & var
scoping:-
The main difference b/w the two is scoping rules. Variables declared by var are scoped to the immediate function body while let variables are scoped to the immediate enclosing block.
function print() {
{
var name = "Hassan";`enter code here`
let userid = "arafath007";
console.log(name); // Hassan
console.log(userid); // arafath007
}
console.log(name); // Hassan
console.log(userid); // ReferenceError
}
print();
Hoisting:-
Variables declared with both let & var are hoisted. Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Variables declared with var are initialized with undefined before the code is run. So, they are accessible in their enclosing scope even before they are declared:
function print() {
console.log(name); // undefined
var name = "Hassan";
console.log(name); // Hassan
}
print();
let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in ReferenceError.
function print2() {
console.log(name); //ReferenceError
let name = "Hassan";
console.log(name); // Hassan
}
print2();
So, use let when you know that the value of an identifier will change. Use const when the identifier value is constant, wont change. Avoid using var because it causes confusion & bugs.