JavaScript : Array Const

In JavaScript, you can use the const keyword to declare a constant array. When you declare an array using const , the variable itself cannot be reassigned to a different array. However, the contents of the array can still be modified.

Here's how you can declare a constant array:


const colors = ['red', 'green', 'blue'];
 

Once declared, you cannot assign a new array to the colors variable:


colors = ['yellow', 'orange']; // Error: Assignment to constant variable.
 

However, you can still modify the contents of the array:


colors.push('yellow');
console.log(colors); // Output: ['red', 'green', 'blue', 'yellow']

 


colors[0] = 'purple';
console.log(colors); // Output: ['purple', 'green', 'blue']

 

Using const with arrays ensures that the variable itself cannot be accidentally reassigned to a different array, which can help prevent unintended side effects in your code. However, it's important to note that const only protects the variable reference, not the contents of the array. If you need to ensure that the array itself cannot be modified, you can use techniques like freezing the array using Object.freeze() or using immutable data structures.