How to Change Values in an Array While Doing For Each in JavaScript – Definitive Guide

ForEach executes a function in every array element once.

You can change values in an array while doing foreach in JavaScript by accessing and assigning a new value during each iteration.

This tutorial teaches you the different methods to change values in an array while doing foreach.

  • Foreach does not make a copy of an array before iterating
  • Foreach does not mutate the same array. However, you can use a call-back function to mutate the same array during iteration

Refer to the foreach documentation for more details on the dos and don’ts.

Concurrent modification frequently leads to hard-to-understand code. Generally, it must be avoided except in special cases. You can use the map() method to create a new array with the desired elements

Change Values in an Array Using ForEach And Arrow Function

This section explains how to use the arrow function to update array values while doing foreach.

While doing foreach with the arrow function, the current element and the index are available.

You can use the index and set a new value at that specific array position.

Use the arrow function when you use simple statements during each iteration, and there is no need for a this reference inside the function. Because the value of this varies by scope and context.

Code

The following code demonstrates how to use the arrow function with foreach to modify the array value.

During each iteration, the square of the number is calculated and assigned to the same array position.

const numArray = [1, 2, 3, 4, 5];

numArray.forEach((element, index) => {
  numArray[index] = element * element;
});

console.log(numArray);

Output

[1, 4, 9, 16, 25]

Change Values in an Array Using ForEach and CallBack Function

This section explains how to use a callback function with foreach to update an array.

During each iteration of the foreach, the function will have the current element and the current index. Also, you can pass the additional element that needs to be used for this reference.

Using the current index and this reference, you can change the value of the array.

Use this method when you want to use complex statements in the callback function or invoke an already-defined callback function to update the array’s values.

Code

During each iteration, the square of the number is calculated and assigned to the same array position using the callback function.

const numArray = [1, 2, 3, 4, 5];

numArray.forEach(function(element, index) {
  this[index] = element * element;
}, numArray);

console.log(numArray);

Output

[1, 4, 9, 16, 25]

This is how you can modify the array value while doing foreach in JavaScript.

Additional Resources

Leave a Comment