How to Increment the Values in an Array in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 14 20212 min read

Increment the Values in an Array #

To increment the values in an array, use the map() method to iterate over the array and on each iteration return the value, e.g. arr.map(element => element + 1). The map() method will return a new array that contains the incremented values.

index.js
const arr1 = [1, 2, 3]; const newArr = arr1.map(element => element + 1); // ๐Ÿ‘‡๏ธ [2, 3, 4] console.log(newArr);

The function we passed to the Array.map method gets called with each element in the array.

On each iteration, we increment the value by 1 and return the result.

The map method does not mutate the original array, it returns a new array.

Alternatively, you can increment the values in place, using the Array.forEach method.

To increment the values in an array:

  1. Use the forEach() method to iterate over the array.
  2. On each iteration, increment the current value.
  3. The final array will contain the incremented values.
index.js
const arr2 = [1, 2, 3]; arr2.forEach((element, index) => { arr2[index] = element + 1; }); // ๐Ÿ‘‡๏ธ [2, 3, 4] console.log(arr2);
The function we passed to the forEach() method gets called for each element in the array.

On each iteration, we make use of the value and the index to increment the current element in the array by 1.

As opposed to the map method, which returns a new array, the forEach() method returns undefined. This means that we change the original array in place.

In general, it's best to avoid mutating the same array/object multiple times, at different places in the same codebase, so I'd go with the map() method.

Mutations on the same objects/arrays are difficult to reason about and track throughout a codebase, however, if you only have to mutate the array once, you could go with either approach.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee