# Update all elements in an array using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 11, 2022, updated Jun 10, 2023. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-update-all-elements-in-array

> Learn how to use the forEach() and map() methods to update all elements in an array using JavaScript.

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

1. Utilize the [`Array.forEach()`](https://attacomsian.com/blog/javascript-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:

```javascript
const birds = ['?', '?', '?', '?']

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

console.log(birds)
// 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 `Array.map()` method:

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

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

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

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

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