JavaScript Arrays with const
In JavaScript, declaring an array with const
means the reference to the array cannot be changed, but the contents of the array remain mutable.
- You can modify, add, or remove elements.
- You cannot reassign the array to a new one.
Example 1: Modifying Array Contents
const fruits = ["Apple", "Banana", "Mango"];
// Modify elements
fruits[0] = "Orange";
// Add new element
fruits.push("Kiwi");
console.log(fruits);
// Output: ["Orange", "Banana", "Mango", "Kiwi"]
// Reassigning the array is NOT allowed
// fruits = ["Pineapple"]; // TypeError
Example 2: Using Array Methods
const numbers = [1, 2, 3, 4];
numbers.pop(); // removes 4
numbers.push(5); // adds 5
console.log(numbers); // [1, 2, 3, 5]
Important Notes
Block Scope
const
arrays are block-scoped, like let
.
if (true) {
const temp = [1, 2, 3];
console.log(temp); // [1, 2, 3]
}
// console.log(temp); // Error: temp is not defined
Must Be Initialized
A const
array must be assigned a value during declaration.
// const arr; // Error
const arr = []; // Correct
Making an Array Immutable
const
does not make the array itself immutable. Use Object.freeze()
to prevent modifications:
const nums = Object.freeze([1, 2, 3]);
nums.push(4); // Error in strict mode
Object.freeze()
is shallow. Objects inside the array can still be modified:
const arr = Object.freeze([{name: "John"}]);
arr[0].name = "Doe"; // Allowed