let and const came with ES2015 and are what modern code uses.
let: a variable that can change
let count = 0;
count = count + 1;
count += 1;
console.log(count); // → 2
const: a name that cannot be reassigned
const siteName = "Deepak Paswan";
console.log(siteName); // → Deepak Paswan
siteName = "Another name"; // error on purpose: assignment to a constant
Run it and read the error: Assignment to constant variable. A const must also get its value in the same line: const x; is a syntax error.
const does not freeze the contents
This surprises people. const stops you from pointing the name at something else. It does not stop the thing itself from changing.
const user = { name: "Maya", age: 25 };
user.age = 26; // allowed: we changed the object's content
console.log(user.age); // → 26
const list = [1, 2];
list.push(3); // allowed
console.log(list); // → [1, 2, 3]
You can change what is inside an object or array, but you cannot do user = somethingElse.
Block scope
Both let and const live only inside the nearest pair of curly braces { }. That is called block scope.
if (true) {
let inside = "I only exist in here";
const alsoInside = 42;
console.log(inside); // → I only exist in here
}
console.log(typeof inside); // → undefined
Outside the block, inside does not exist. Block scope keeps variables where they are needed and prevents accidents. You will see more about this in Scope.
The temporal dead zone
You cannot use a let or const before the line that declares it.
console.log(early); // error on purpose: cannot access before initialization
let early = 5;
Which one should I use?
const. Switch to let only when you know the value has to change. See Choosing Between let, const and var.