Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To change the value of all elements in an array:
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.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 could have achieved the same result by using a plain for
loop. However,
for
loops are a bit more verbose and indirect.
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.
map
method to achieve this.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.