Changing an Array Element in JavaScript

To change an element in a JavaScript array, use the index number with square brackets [] and assign a new value to it. Arrays are zero-indexed, meaning the first element is at index 0.

Key Points

  • Index Assignment: Use the index to access and change the value.
  • Zero-Indexed: The first element is at index 0.

Examples

Changing an Element

let fruits = ['Apple', 'Banana', 'Orange'];
fruits[1] = 'Mango';
console.log(fruits); 

// Output: ['Apple', 'Mango', 'Orange']

Here, we changed the element at index 1 from 'Banana' to 'Mango'.

Adding a New Element at a Specific Index

You can also add an element at an index that doesn’t currently have a value:

fruits[3] = 'Grapes';
console.log(fruits); 

// Output: ['Apple', 'Mango', 'Orange', 'Grapes']

This adds 'Grapes' to index 3 of the array.

Practical Tips

Out of Bounds: Adding an element at an index greater than the current length will leave empty slots in between.

  fruits[5] = 'Peach';
  console.log(fruits); 
  
  // Output: ['Apple', 'Mango', 'Orange', 'Grapes', <1 empty item>, 'Peach']

Avoiding Undefined: Be careful when accessing indices that don’t exist, as this will return undefined.