DEV Community

Discussion on: .map() vs .forEach()

Collapse
 
torianne02 profile image
Tori Crawford

First off, Alexander, thank you for taking the time to comment on my post. I always appreciate when people take the time to engage with others here on DEV.

Secondly, unfortunately, you are incorrect in regards to mutation. .forEach does not mutate the array it is called on and has a return value of undefined. Here is a link to the documentation for you to read.

With the code you are addressing, the purpose was not to mutate the original array, dogs, but to save the output of the function being passed into the iterator to the new result array.

You can see in the screenshot of a Repl.it I created to test the code below, that my code does NOT mutate the original array.

screenshot of my above code ran on repl.it

Now you'll notice in a screenshot using your code, that it ALSO DOES NOT mutate the dogs array.

screenshot of Alexander's code on repl.it

The point of this article was to discuss two different types of array iterators. If you read the entire article from start to finish you would have hopefully noticed the Final Thoughts section which states

If you want to iterate over an array without needing the results of the function to be saved, then I suggest using .forEach(). Opposite of this, if you need the results of the function in order to execute other code that depends on it, use .map().

With this, I am saying that if you ever need the results of what you are receiving from the array iterator, then .forEach isn't what you want to use since it requires more code. .map is what you'd want to use instead.

Now, please in the future, when you comment on someone's post here on DEV, please don't use passive-aggressive phrases like "Don't misinform people." You should politely correct it.