JavaScript Array Const

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']

Try It Now

Key Points:

  • You cannot reassign a new array to the fruits variable.
  • 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']

Try It Now

Key Points:

  • You can update, add, or remove elements from the array.
  • The array’s size and content can be changed, but the variable fruits still 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.

Try It Now

Key Points:

  • The reference to the array cannot be changed.
  • You cannot assign a new array to the const variable.

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]

Try It Now

Using const for Arrays: Best Practices

  • Use const when you want to ensure the reference to the array remains constant.
  • Use const to avoid accidental reassignment of the array.
  • You can still modify the array’s contents safely.

Summary

  • const creates a constant reference to the array, but the contents of the array can be modified.
  • Attempting to reassign a new array to a const variable will result in an error.
  • It is recommended to use const for arrays to prevent reassignment and potential bugs, while still allowing content modification.