Different Between Let vs Const in JavaScript
Difference Between let and const in JavaScript
Both let and const are used to declare variables in JavaScript, but they have key differences in mutability and reassignment.
1. Mutability
Variables declared with let can be reassigned, whereas variables declared with const cannot be reassigned.
// Using let
let x = 10;
x = 20; // Allowed
// Using const
const y = 30;
y = 40; // Error: Assignment to constant variable
2. Re-declaration
let allows reassignment but not re-declaration in the same scope, while const does not allow reassignment at all.
// let allows reassignment
let a = 5;
a = 10; // Works
// const does not allow reassignment
const b = 15;
b = 20; // Error
3. Object & Array Mutation
const does not allow variable reassignment, but objects and arrays declared with const can be modified.
const obj = { name: "John" };
obj.name = "Doe"; // Allowed
const arr = [1, 2, 3];
arr.push(4); // Allowed
obj = {}; // Error: Assignment to constant variable
Conclusion
Use let when you need to change the variable's value. Use const when the variable should remain unchanged, but note that objects and arrays can still be modified.