Array.prototype.reduce()
Array.prototype.reduce() is a JavaScript method in the Array category. Executes a reducer function on each element, resulting in a single output value. The syntax is array.reduce(callbackFn, initialValue). It accepts callbackFn(accumulator, currentValue, index, array). It returns the single value that results from the reduction. A typical example: [1, 2, 3].reduce((acc, x) => acc + x, 0) // 6. Another practical use — Sum all numbers: const nums = [1, 2, 3, 4, 5] const sum = nums.reduce((a, b) => a + b, 0) console.log(sum) // 15 Another practical use — Group objects by key: const items = [{ type: 'fruit', name: 'apple' }, { type: 'fruit', name: 'banana' }, { type: 'veg', name: 'carrot' }] const grouped = items.reduce((acc, item) => { (acc[item.type] = acc[item.type] || []).push(item.name) return acc }, {}) console.log(grouped) Common pitfall — Always provide an initial value. Without an initial value, reduce() on an empty array throws a TypeError. Always provide the initial value. Common pitfall — Don't use reduce() for simple sums. For simple sums, forEach() or a for loop is more readable. Use reduce() for complex transformations. Its time complexity is O(n), which matters when it runs over large inputs. The TypeScript signature is <T>(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T. reduce() is the most general of the array iteration methods: everything map(), filter(), and flatMap() do can also be expressed as a single reduce(), because the accumulator may be any type — a number, an array, an object, a Map, even a promise. That generality is why reduce() appears wherever many values must collapse into one shape: summing totals, counting occurrences into a tally object, grouping items by a computed key, flattening nested arrays, removing duplicates, and building lookup tables in one pass. The initial-value argument deserves particular attention. Without it, reduce() uses the first element as the accumulator and starts iterating at index 1, which throws on an empty array and quietly produces surprising types on mixed content; passing an explicit initial value — 0 for sums, an empty array for collections, an empty object for tallies — removes both problems and makes the return type obvious to readers. Performance-minded code should also watch the accumulator pattern: building with spreads such as spreading the accumulator plus the new item turns a single O(n) pass into a quadratic loop, while pushing into the array held by the accumulator stays linear. When a plain loop would be clearer, or when the reduction spans many lines, consider whether a for...of loop with a local variable communicates the intent better.