Facebook Pixel

Why does reduce throw TypeError on 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 it throws TypeError: Reduce of empty array with no initial value. Always pass an initial value.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Common Higher-Order Function Mistakes in JavaScript

Because map returns a new array, which is wasted if you only want side effects. forEach returns undefined and signals that you are not transforming data. Using map for side effects is misleading and wastes memory.

Because sort defaults to string comparison. It converts elements to strings and sorts lexicographically. '10' comes before '2' because '1' < '2'. Use a numeric comparator: sort((a, b) => a - b).

Because the arrow function has a block body (braces) with no return statement. Block bodies need an explicit return. Use an expression body (n => n * 2) or add return (n => { return n * 2; }).

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.