JavaScript Array with const – Understand Mutability
In JavaScript, you can declare arrays using the const keyword. This creates a constant reference to the array, meaning that the reference to the array cannot be changed. However, the contents of the array (i.e., its elements) can be modified.
Declaring an Array with const
const fruits = ['Apple', 'Banana', 'Cherry']; console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry']
Key Points:
- You cannot reassign a new array to the
fruitsvariable. - You can modify the elements within the array.
Modifying an Array Declared with const
Although the reference to the array is constant, you can still change the array’s contents.
const fruits = ['Apple', 'Banana', 'Cherry'];
fruits[0] = 'Mango'; // Modify element
fruits.push('Orange'); // Add new element
console.log(fruits); // Output: ['Mango', 'Banana', 'Cherry', 'Orange']
Key Points:
- You can update, add, or remove elements from the array.
- The array’s size and content can be changed, but the variable
fruitsstill points to the same array.
Attempting to Reassign a const Array
Trying to reassign the const array will result in an error.
const fruits = ['Apple', 'Banana']; // fruits = ['Mango', 'Peach']; // Uncaught TypeError: Assignment to constant variable.
Key Points:
- The reference to the array cannot be changed.
- You cannot assign a new array to the
constvariable.
Example of Using const with Arrays
Here’s an example that shows modifying an array declared with const:
const numbers = [1, 2, 3]; numbers.push(4); // Adds 4 to the array console.log(numbers); // Output: [1, 2, 3, 4] numbers[1] = 10; // Updates the second element console.log(numbers); // Output: [1, 10, 3, 4]
Using const for Arrays: Best Practices
- Use
constwhen you want to ensure the reference to the array remains constant. - Use
constto avoid accidental reassignment of the array. - You can still modify the array’s contents safely.
Summary
constcreates a constant reference to the array, but the contents of the array can be modified.- Attempting to reassign a new array to a
constvariable will result in an error. - It is recommended to use
constfor arrays to prevent reassignment and potential bugs, while still allowing content modification.