Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript forEach: mutate elements

I want to use forEach on an array. Since forEach is a mutator, it should mutate the values in the original array, but it's not. What's the issue here?

let array = [1, 2, 3, 4]; //simple array declaration

array.forEach((ele) => ele * 2); //using forEach to double each element in "array"

console.log(array); //logs [1,2,3,4] instead of [1,4,6,8]

What's going on here?

like image 657
Manas Dixit Avatar asked Jun 22 '26 10:06

Manas Dixit


1 Answers

No, forEach does not mutate the original array.

You can achieve what you are looking for by giving a second parameter of index, then updating the values of the original array.

let array = [1, 2, 3, 4];
array.forEach((ele, index) => array[index] = ele * 2);

console.log(array);

documentation for forEach

like image 189
ahsan Avatar answered Jun 25 '26 00:06

ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!