DEV Community

Benjamin Alan Murphy-Kane
Benjamin Alan Murphy-Kane

Posted on

.forEach vs .map: A Short Summary

Two very important array iteration methods that you will be seeing when using java are .forEach and .map, both going through an array and enacting a function on each element. But how do they differ in usage and purpose? In this post, I will be explaining key differences and elements that differ these two methods.

First is .forEach, an iteration method that will call a function for each element in an array. One important thing to note is that .forEach will go through every single element in the array it is used on without mutating it. There are three five parameters to use in .forEach, with two of them being required to run the function, these two being the function that is going to be run onto the array and currentValue, the value/array that the function is being run on.

The three optional parameters here are the index of the current element index, the array of the current element if you are working on something that is nested, arr and thisValue which will pass the parameter entered as its this value.

Moving onto .map, .map will, just like .forEach, call a function onto an array, but the real question is... which array? To which I answer, a copy, of course!

.map creates a copy of the original array and calls a function onto every element in said copy. One difference that stands out from .forEach is that .forEach creates a copy of the array, which is useful for preventing accidental mutations or changes in the array. And while I said earlier that .forEach doesn't change the array, that was a bit of a lie. Any callback function provided in .forEach's parameter may cause a mutation depending on what you want the function to do.

.map takes the same parameters as .forEach, which at first fooled me when I was in the process of learning iteration methods for arrays. Understand that when you use .map, the array that you iterate over is a copy of the original, preventing the data modified from being applied to the original array and returning that modified copy, whereas .forEach. iterates the function over that exact array.

Top comments (0)