Computer >> Computer tutorials >  >> Programming >> Javascript

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


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.