Map, Filter, and Reduce: The Foundations of Functional JavaScript
These three methods shape how I think about data transformation. Here is how to use them well and when to stop. Map, filter, and reduce are the trinity of functional array processing in JavaScript. They each take a callback and return a new array (or, for reduce, a single accumulated value), leaving the original array untouched. Once these clicked for me, I stopped writing for loops for most data transformation and my code became shorter and more declarative. Map Transforms Every Element Map applies a function to every element and returns a new array of the same length. The output array always has the same number of elements as the input. I use map when I want to translate one shape of data into another, like converting raw API records into view-model objects. The callback receives the element, its index, and the source array, though I usually only need the element. const prices = [10, 25, 40]; const withTax = prices.map(p => p * 1.2); // [12, 30, 48] Filter Keeps What Matches Filter applies a predicate and keeps only the elements for which the predicate returns a truthy value. The…