Intro
When you use const to declare objects or arrays in JavaScript, you’re making the variable binding (the reference) immutable — not the contents themselves.
This means you cannot assign a new array or object to that variable, but you can still change the data inside the object or array.
For example:
const c = [1, 2]; // c is bound to a specific array
If you try to reassign c to a new array:
c = [3, 4]; // This will cause an error: Assignment to constant variable
The error occurs because const prevents changing what c points to.
However, you can modify the elements within the array:
c[0] = 5; // Allowed: changes the value at index 0
console.log(c); // Output: [5, 2]
This works because const only protects the binding (the reference to the array), not the array’s contents.
Summary
Declaring an array or object with const means the variable must always point to the same array or object. However, you are free to update, add, or remove items within that array or object. The reference stays constant, but the internal data can change.
Top comments (0)