Js Array Const in JavaScript
?? const with Arrays in JavaScript
Can You Use const with Arrays?
Yes! You can declare arrays with
const.constmeans the variable reference cannot be reassigned, but the contents of the array can be changed (mutated).
Example: Declaring an Array with const
const fruits = ["apple", "banana", "cherry"];Modifying the Array Contents (Allowed)
You can change elements, add, or remove items even if declared with const:
fruits[1] = "blueberry"; // Modify elementfruits.push("date"); // Add elementfruits.pop(); // Remove last elementconsole.log(fruits); // ["apple", "blueberry", "cherry"]Reassigning the Array (Not Allowed)
fruits = ["kiwi", "mango"]; // ? Error: Assignment to constant variable.You cannot reassign the variable
fruitsto a new array or any other value.
Why Use const with Arrays?
Prevents accidental reassignment of the variable reference.
Ensures your variable always points to the same array instance.
Still allows flexibility to change the array content.
Summary
| Operation | Allowed with const Arrays? |
|---|---|
| Modify elements | ? Allowed |
| Add or remove elements | ? Allowed |
| Reassign array variable | ? Not Allowed |
Want examples on immutability patterns with arrays or how to use let vs const with arrays?