JavaScript Array Const
8 April 2025 | Category: JavaScript
In JavaScript, you can declare an array using const
to make sure the variable cannot be reassigned. But remember: const
does not make the array immutable — you can still modify its contents.
✅ Declaring an Array with const
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits); // ["Apple", "Banana", "Mango"]
🔹 You must assign a value when using
const
. You cannot declare it and assign later.
❌ Reassignment is Not Allowed
const colors = ["Red", "Green"];
colors = ["Blue", "Yellow"]; // ❌ Error: Assignment to constant variable
You cannot reassign a new array to the same
const
variable.
✅ But You CAN Modify the Elements
You can add, remove, or change elements in a const
array.
const numbers = [1, 2, 3];
numbers[0] = 10; // ✅ Changing an element
numbers.push(4); // ✅ Adding an element
numbers.pop(); // ✅ Removing last element
console.log(numbers); // [10, 2, 3]
const
protects the binding, not the data inside the array.
✅ When to Use const
with Arrays
- Use
const
when the reference should not change. - It helps prevent bugs caused by accidental reassignment.
- Still gives flexibility to work with the array contents.
📌 Summary
Feature | Behavior with const Arrays |
---|---|
Reassigning the whole array | ❌ Not allowed |
Modifying values | ✅ Allowed |
Using array methods (push , pop , etc.) | ✅ Allowed |
Must assign a value initially | ✅ Yes, required |
🧠 Final Note
Using const
with arrays is a best practice when you want to:
- Maintain a fixed reference
- Avoid reassignment errors
- Still work with the array data flexibly