const: Reference Binding & ImmutabilityDeclaring an array with const prevents reassignment of the array identifier variable, but it does NOT freeze the elements contained within the array instance.
const Binding Rulesflowchart TD
ConstArr["const list = [1, 2, 3]"] --> ReassignAttempt{"Attempt list = [4, 5]?"}
ReassignAttempt -- "Yes" --> Err["TypeError: Assignment to constant variable"]
ConstArr --> MutateAttempt{"Attempt list.push(4) or list[0] = 99?"}
MutateAttempt -- "Yes" --> Allowed["Operation Allowed! Array reference is fixed, content is mutable."]
| Action | Code Example | Allowed on const Array? |
|---|---|---|
| Reassign Variable | list = ["new", "array"]; |
No (TypeError) |
| Push / Pop Elements | list.push("item"); |
Yes |
| Mutate Element by Index | list[0] = "updated"; |
Yes |
| Mutate with Splice | list.splice(0, 1); |
Yes |
| Freeze Contents | Object.freeze(list); |
Makes array elements read-only. |
// Demonstrating const array reference behavior and Object.freeze
// 1. Const Array Mutation Allowed
const numbers = [10, 20, 30];
numbers.push(40); // Allowed
numbers[0] = 99; // Allowed
console.log("Mutated const numbers array:", numbers); // [99, 20, 30, 40]
// 2. Reassignment Throws Error
try {
// numbers = [1, 2, 3]; // Un-commenting throws TypeError
} catch (err) {
console.error(err.message);
}
// 3. True Immutability with Object.freeze()
const immutableList = Object.freeze([1, 2, 3]);
// In non-strict mode mutates silently fail; in strict mode throws TypeError
// immutableList.push(4); // Throws TypeError: Cannot add property 3, object is not extensible
console.log("Frozen List:", immutableList);
const: Using const for arrays prevents accidental variable overwrites while allowing necessary element operations.Object.freeze() is Shallow: Object.freeze() prevents adding, deleting, or editing top-level array elements, but objects nested inside the frozen array remain mutable unless recursively frozen.const array, use spread syntax: const updated = [...original, newItem].Explain the difference between const arr = [1, 2]; arr.push(3); and let arr = [1, 2]; arr = [...arr, 3];.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.