Is it possible to change values of the array when doing foreach() in javascript?

JavascriptFront End TechnologyObject Oriented Programming

Yes it is possible to change values of the array when doing foreach() in javascript.

Let us take an example to see this −

Example

let arr = [1, 2, 3, 4];
arr.forEach((val, index) => arr[index] = val * val);
console.log(arr);

Output

This will give the output −

[ 1, 4, 9, 16 ]

We've modified the actual array here when iterating over it using forEach.

raja
Published on 02-Dec-2019 06:21:13
Advertisements