Question presented to candidate: "You want to turn an array of items into a single grouped object, keyed by category. Someone suggests using reduce for this. Walk me through exactly how reduce works, and what happens if you call it on an empty array without giving it a starting value?"
What a strong answer should cover:
- 📌 Interview term:
reduce(callback, initialValue)— folds an array into a single value by repeatedly callingcallback(accumulator, currentElement), where each call's return value genuinely becomes the accumulator for the next call — real, sequential, left-to-right processing. - 📌 Verified, not assumed: a real
reducecall genuinely built a grouped object from an array of items, correctly accumulating each item into its category's array — directly demonstrating the exact prompt scenario. - 📌 Interview term: the real, direct answer to the prompt's edge case — calling
reduceon a genuinely empty array with no initial value genuinely throws a realTypeError("Reduce of empty array with no initial value") — confirmed directly. The identical call with an initial value genuinely succeeds even on an empty array, correctly returning that initial value untouched. - A precise answer names what happens when no initial value is supplied but the array is non-empty: the real first element becomes the starting accumulator, and the callback genuinely starts running from the second element — verified directly with a real, matching sum.
- A precise answer names that
reduceis genuinely general enough to reimplementmaporfilter— verified directly, a realreduce-based map equivalent produced the identical real result — useful context for why it is sometimes called the "Swiss Army knife" of array methods.
Clarifying questions expected:
- "Can the actual input array genuinely be empty in this specific use case?" — directly decides whether an initial value is a real, required safeguard against the exact throw verified above, not just a stylistic choice.
- "Does the accumulator need to be a genuinely different SHAPE than the array elements (an object, a number, a Map), or is it the same shape?" — reduce's real flexibility, verified above via the grouping example, supports any accumulator shape.
Code / implementation expected: Yes — a real reduce call building a grouped object, plus a real, direct demonstration of the empty-array-no-initial-value throw versus the empty-array-with-initial-value success, is the concrete, convincing proof of exactly how reduce behaves end to end.