Facebook Pixel

Why does reduce throw TypeError for an empty array 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.

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.

Four arguments: the accumulator, the current element, the current index, and the array itself. Most callbacks only use the first two, but the polyfill should pass all four to match the spec.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.