Changing Array Values Using ForEach Loop

JavaScript

26/07/2021


Take this array as an example,

JAVASCRIPT
const numbers = [1, 2, 3, 4, 5]

and let's add 1 to each element. The forEach method makes this really easy.

JAVASCRIPT
numbers.forEach((number, index, array) => {
array[index] = number + 1
})
console.log(numbers) // Array(5) [ 2, 3, 4, 5, 6 ]

The trick is to use a 3rd argument in the callback function that gives you access to the array. Be aware that this operation mutates the original array.


WRITTEN BY

Code and stuff