Understanding arrays in javascript
- Transforms each element using a callback function
- Tests each element with a callback that returns boolean
- Executes a reducer function on each element
JavaScript provides three essential array methods for functional programming: map(), filter(), and reduce(). These methods process arrays without mutating the original, returning new arrays or values instead.
map() without using the returned array — use forEach() for side effects instead(accumulator, currentValue, currentIndex, array)reduce() on an empty array without an initial value throws a TypeErrorThese methods return arrays (except reduce()), so they can be chained: arr.filter(...).map(...).reduce(...). This enables a declarative, pipeline-style approach to data transformation.
These are Array.prototype methods. To use them on objects, convert first with Object.keys(), Object.values(), or Object.entries().
Key Interview Distinction: map() vs forEach()
map() returns a new array and is chainable. forEach() returns undefined and cannot be chained. Use map() for transformations, forEach() for side effects.
Fun Fact
JavaScript's Array.prototype was dramatically expanded in ES5 (2009) with map, filter, reduce, forEach, and others — before that, developers relied on for loops for everything. Douglas Crockford's 'JavaScript: The Good Parts' (2008) didn't even mention these methods because they didn't exist yet.