DEV Community

Discussion on: JS Array Manipulation Quirks

Collapse
 
karataev profile image
Eugene Karataev

forEach doesn't mutate an array. Mutation happens only if you explicitly mutate array items in iteration function.

Collapse
 
link2twenty profile image
Andrew Bone • Edited

I guess if you're using forEach like map you could say it mutates

arr.forEach(a => a = {id: a})

// VS

const newArr = arr.map(a => {id: a})

// VS

const newArr = [];
arr.forEach(a => newArr.push({id: a}))
Collapse
 
karataev profile image
Eugene Karataev

Well, actually if we execute your examples, we can notice that forEach doesn't mutate the original array.
forEach

Thread Thread
 
jenc profile image
Jen Chan • Edited

Thanks for pointing that out. This seems like a gray area. I don't know how I got under the impression that forEach mutates the original array items, maybe it was this post I looked up as I was writing the post. It's not entirely clear to me what forEach actually returns if I ran it on an array its own.

I have around the web read general opinions that forEach iterates straight through arrays without breaking, and skips empty values, so that if one wanted to include a condition it would be easier to go with a for-loop. I don't have enough experience with forEach to tell, tbh

Thread Thread
 
belvederef profile image
Francesco Belvedere

To address your point "what forEach actually returns", the answer is "nothing". forEach does not return a value, it is a void function.

Thread Thread
 
jenc profile image
Jen Chan

Thank you! That makes a lot of sense.