What are common mistakes when writing a reduce polyfill in an interview?
Not handling the no-initial-value case (use first element as accumulator), not throwing TypeError for empty arrays, not passing all four arguments to the callback, and using var in the loop (closure bug with async callbacks).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Writing Polyfills for filter and reduce in JavaScript
Add a method to Array.prototype that loops through the array, calls the callback with (element, index, array), and pushes the element to a result array if the callback returns truthy. Return the result array.
Handle the initial value: if provided, start with it at index 0; if not, use the first element and start at index 1. Loop through, calling callback(accumulator, element, index, array). Return the final accumulator. Throw TypeError for empty arrays without an initial value.
Because without an initial value, reduce uses the first element as the accumulator. An empty array has no first element, so the spec throws TypeError: Reduce of empty array with no initial value.
Still have questions?
Browse all our FAQs or reach out to our support team
