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.

JavaScript
1const items = ["pen", "book", "eraser"];

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.

JavaScript
1const colors = ["red", "blue", "green"];
2colors[1] = "yellow";
3colors.push("black");
4console.log(colors);

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.

JavaScript
1const numbers = [1, 2, 3];
2// numbers = [4, 5, 6]; // Error

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)

JavaScript
1const list = ["a", "b"];
2list.push("c"); // mutation (allowed)
3// list = ["x", "y"]; // reassignment (not 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.

JavaScript
1const data = ["x", "y", "z"];
2Object.freeze(data);
3
4data.push("w"); // Fails silently or throws error in strict mode

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 const makes arrays completely immutable

  • Trying to reassign a const array

  • Forgetting that array methods like push() mutate the array

  • Expecting Object.freeze() to deeply freeze nested arrays


Summary of const with Arrays

ConceptBehavior
const referenceCannot be reassigned
Array contentsCan be changed
MutationAllowed
ReassignmentNot 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.