How to update all elements in an array using JavaScript

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}`
})

console.log(birds)
// [ '🐦 -> 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 Array.map() method instead:

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

const updated = original.map((item, index) => {
  return `${item} -> ${index}`
})

console.log(updated)
// [ 'zero -> 0', 'one -> 1', 'two -> 2' ]

console.log(original)
// [ 'zero', 'one', 'two' ]

The Array.map() 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.