To update all elements in an array using JavaScript, you can follow the steps below:

  1. Utilize the Array.forEach() method to iterate over the array. This method takes a callback function as an argument, which receives the array element, its index, and the array itself.
  2. The callback function is executed for each element in the array, starting from the first element.
  3. Inside the callback function, modify the corresponding array element using its index.

Here's an example:

const birds = ['🐦', '🦅', '🦆', '🦉']

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

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

The Array.forEach() method was introduced in ES6. It executes the provided callback function once for each element in the array, in ascending order. Empty array elements are not processed by the callback function.

If you prefer not to modify the original array and instead create a new array with the updated elements, you can use the method:

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

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

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

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

The method invokes the provided callback function for each element in the array. It doesn't modify the original array and instead relies on the callback function's results to create a new array.

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