Prompt
Implement your own version of Array.prototype.reduce as myReduce(arr, callback, initialValue).
Handle both arities correctly:
- With an initial value — even an explicit
undefinedcounts as provided (detect viaarguments.length, not=== undefined) - Without one — the first element seeds the accumulator and iteration starts at index 1
- Empty array with no initial value must throw a TypeError (per spec)
Solution
Reduce is the hardest of the trio because its contract has a genuine subtlety: "no initial value" and "initial value is undefined" are different calls that must behave differently. The spec distinguishes them by argument count, so the implementation checks arguments.length >= 3 — not initialValue === undefined, which conflates the two and is precisely the bug this challenge's fourth test catches. Passing undefined explicitly means "seed the accumulator with undefined and run the callback from index 0"; omitting it means "the first element is the seed, start at index 1."
The two arities cascade through the whole function: seed selection (initialValue vs arr[0]), loop start (0 vs 1), and the edge case — an empty array with no seed has nothing to return, so the spec mandates a TypeError. Throwing there isn't defensive over-engineering; silently returning undefined turns a caller's bug into corrupted downstream data. This is the same declared-vs-assigned distinction that runs through JavaScript (hoisting, missing keys vs undefined values in deepEqual) — sensing when undefined is a value versus an absence is a recurring senior tell.
Practical guidance to volunteer: always pass an initial value in application code — it makes empty inputs safe and the accumulator type explicit.
Red flag: var acc = initialValue !== undefined ? initialValue : arr[0]. It passes the happy-path tests and misfires on both explicit-undefined seeds and any array whose reduction legitimately produces undefined.
Say it: "I detect the seed by arity — arguments.length, never an undefined check — because omitted and explicitly-undefined are different contracts, and empty-plus-no-seed throws per spec."