How to Modify all Array Elements in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Modify all Elements in an Array #

To change the value of all elements in an array:

  1. Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself.
  2. Use the index of the current iteration to change the corresponding array element.
index.js
const arr = ['a', 'b', 'c']; arr.forEach((element, index) => { arr[index] = element + index; }); console.log(arr); // 👉️ ['a0', 'b1', 'c2']

The function we passed to the Array.forEach() method gets invoked with each element, its corresponding index and the entire array.

We used the index to change the value of the array element at the specific position.

We could have achieved the same result by using a plain for loop. However, for loops are a bit more verbose and indirect.

index.js
const arr = ['a', 'b', 'c']; for (let index = 0; index < arr.length; index++) { arr[index] = arr[index] + index; } console.log(arr); // 👉️ ['a0', 'b1', 'c2']

It's a matter of personal preference, but in my opinion the forEach() approach is more readable and intuitive.

Most experienced developers avoid mutating arrays and objects. Instead, they create new arrays containing the desired elements. We can use the map method to achieve this.
index.js
const arr = ['a', 'b', 'c']; const newArr = arr.map((element, index) => { return element + index; }); console.log(newArr); // 👉️ ['a0', 'b1', 'c2'] console.log(arr) // 👉️ ['a', 'b', 'c']

We used the Array.map method in a very similar way to how we used the forEach method.

However, this time we don't change the elements in the original array. Instead, we create a new array containing the modified elements.

Code gets very hard to follow if we mutate the contents of an array multiple times. In my experience, a better approach is to create a new array that only contains the elements we need.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.