To update all elements in an array using JavaScript:

  1. Use the Array.forEach() method to iterate over the array. It accepts a callback function with the array element, its index, and the array itself.
  2. The callback function is invoked for each element in an array in ascending order.
  3. Inside the callback function, use the current element index to modify the corresponding array element.
const birds = ['🐦', '🦅', '🦆', '🦉']

birds.forEach((bird, index) => {
  birds[index] = `${bird} -> ${index}`

// [ '🐦 -> 0', '🦅 -> 1', '🦆 -> 2', '🦉 -> 3' ]

The Array.forEach() method was introduced in ES6, and executes the given callback function once for each element in an array in ascending order. It doesn't invokes the callback function for empty array elements.

The above solution changes the original array in place. If you don't want to mutate the original array, use the method instead:

const original = ['zero', 'one', 'two']

const updated =, index) => {
  return `${item} -> ${index}`

// [ 'zero -> 0', 'one -> 1', 'two -> 2' ]

// [ 'zero', 'one', 'two' ]

The method invokes the given callback function for each element in the array. It does not mutate the original array and relies on the results of the callback function to create a new array.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.