Categories
JavaScript Answers

How to change values in array when using forEach with JavaScript?

Spread the love

To change values in array when using forEach with JavaScript, we can assign the new value.

For instance, we write

const data = [1, 2, 3, 4];
data.forEach((item, i, self) => (self[i] = item + 10));

to call forEach with a callback that has the i and self parameters.

In it, we assign self[i] to the new value of the array.

self is the data array.

i is the index of the entry being iterated through.

item is the entry being iterated through.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *