JavaScript const
The const keyword was introduced in ES6 (2015). Use const when the variable value should not be reassigned. It must be initialised at declaration.
const Cannot Be Reassigned
Immutable Binding
const PI = 3.14159;
console.log(PI);
// PI = 3; // TypeError: Assignment to constant variableconst Must Be Initialised
Initialisation at Declaration
const MAX = 100; // OK
// const LIMIT; // SyntaxError: Missing initializer in const declarationconst Objects Are Mutable
const prevents reassigning the variable, but it does NOT make the object immutable. Properties can still be changed.
const Object — Properties Can Change
const person = { name: "Alice", age: 30 };
person.age = 31; // OK — mutating a property
person.city = "Paris"; // OK — adding a property
console.log(person);
// person = {}; // TypeError — reassigning const is not allowedconst Arrays Are Mutable
const Array — Elements Can Change
const colors = ["red", "green", "blue"];
colors.push("yellow"); // OK — mutating array
colors[0] = "white"; // OK — changing element
console.log(colors);
// colors = []; // TypeError — reassigning const is not allowedconst vs let vs var
| Feature | const | let | var |
|---|---|---|---|
| Scope | Block | Block | Function |
| Reassign | ✗ No | ✓ Yes | ✓ Yes |
| Redeclare | ✗ No | ✗ No | ✓ Yes |
| Must initialise | ✓ Yes | ✗ No | ✗ No |
| Hoisted | TDZ | TDZ | ✓ (undefined) |
📝 Note: Best practice: use const by default. Switch to let only when you know the value needs to change. Never use var in modern code.
Exercise:
Can you change properties of a const object?