I totally understand that sadness!
Believe it or not, as you grow your developer chops, it can actually become a really amazing experience to toss your code because you’ve learned better approaches!
map
, filter
, and reduce
definitely took me a while to wrap my head around, but once I did, it was a major level up in my skills!
This following graphic is a light-hearted, high-level summary of the difference between the three. Despite it’s humor, if you really think about what’s happening it’s actually a great way to think about each method.
(Note: in case it isn’t obvious, the image is not using JavaScript syntax.)
Also, many examples of reduce
use a number as the accumulator, but just like in the image, you can actually accumulate pretty much anything
As for the relationship with loops or iterators, in map, filter, reduce, forEach, and a few others, the iteration is simply being handled for you by the JS engine.
The distinction between map
and forEach
can seem unclear at first, basically, map returns a completely new array, while forEach doesn’t. Because of developer expectations, you should also NEVER mutate the original array using a map (a lot of devs think that you can’t mutate via a map, but you absolutely can, you just really, really shouldn’t!)