Using const with arrays in JavaScript often causes confusion. An array declared with const cannot be reassigned, but its contents can be modified. Understanding the difference between reassignment and mutation is important for writing safe and predictable code.
What Does const Mean in JavaScript?
The const keyword creates a variable whose reference cannot be changed after assignment.
Explanation:
The variable items always points to the same array in memory.
Can a const Array Be Modified?
A const array is mutable, which means elements inside the array can be changed.
Explanation:
-
Elements inside the array can be updated
-
New elements can be added
-
The array reference remains the same
What Is Not Allowed with const Arrays?
Reassigning the entire array is not allowed.
Explanation:
Reassigning a const variable throws an error because the reference cannot change.
Reassignment vs Mutation
-
Reassignment: Changing the variable to point to a new array (not allowed with
const) -
Mutation: Changing the contents of the existing array (allowed)
Explanation:
Mutating the array changes its content, not the variable reference.
Preventing Changes to const Arrays
To prevent modifications to array contents, Object.freeze() can be used.
Explanation:
Freezing the array prevents adding, removing, or changing elements.
When to Use const with Arrays
-
When the variable reference should not change
-
When using arrays as fixed references
-
For safer and more predictable code
Common Mistakes with const Arrays
-
Assuming
constmakes arrays completely immutable -
Trying to reassign a
constarray -
Forgetting that array methods like
push()mutate the array -
Expecting
Object.freeze()to deeply freeze nested arrays
Summary of const with Arrays
| Concept | Behavior |
|---|---|
| const reference | Cannot be reassigned |
| Array contents | Can be changed |
| Mutation | Allowed |
| Reassignment | Not allowed |
| Object.freeze() | Prevents mutation |
Conclusion
Using const with arrays in JavaScript prevents reassignment of the array reference while still allowing changes to its elements. By understanding the difference between reassignment and mutation, and by using Object.freeze() when needed, arrays can be managed safely and predictably in JavaScript applications.