Arrays are Not Constants. The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array.
JavaScript Array Const
In JavaScript, you can create an array using the const
keyword to declare a constant array. Using const
to declare an array means that the variable holding the array cannot be reassigned to a different array or a different value altogether. However, it does not mean that the contents of the array cannot be modified. The individual elements of a const
array can still be changed.
Here’s an example of how you can declare a constant array in JavaScript:
const myArray = [1, 2, 3, 4];
// You can access and modify individual elements of the array
myArray[0] = 99; // This is allowed and changes the first element to 99
console.log(myArray); // Output: [99, 2, 3, 4]
Arrays are Not Constants
The keyword const
is a little misleading.
It does NOT define a constant array. It defines a constant reference to an array.
Because of this, we can still change the elements of a constant array.
In this example, myArray
is a constant array, but we can still modify its elements. What you cannot do with a const
array is reassign it to a different array:
const myArray = [1, 2, 3, 4];
// This will result in an error
myArray = [5, 6, 7];
Attempting to reassign myArray
to a different array will throw an error because myArray
is declared using const
.
To prevent the modification of the array’s contents as well, you can use the Object.freeze()
method:
const myArray = [1, 2, 3, 4];
Object.freeze(myArray);
// These operations will not work and will not modify the array
myArray[0] = 99;
myArray.push(5);
console.log(myArray); // Output: [1, 2, 3, 4]
In this case, Object.freeze()
makes the array immutable, so attempts to modify its elements will have no effect.