What happens here?
const arr = [];
const total = arr.reduce((sum, n) => sum + n);
console.log(total);
- 0
- undefined
- NaN
- TypeError
Hari ![]()
What happens here?
const arr = [];
const total = arr.reduce((sum, n) => sum + n);
console.log(total);
Hari ![]()
TypeError — reduce on an empty array with no initial accumulator throws immediately, so it never even gets to your callback.
It’s like trying to start a running total without a starting number. Give it an initial value and you get what you probably expected: [].reduce((sum, n) => sum + n, 0) → 0.
I’d pick “TypeError” here — reduce on an empty array with no initial value throws immediately, so your callback never runs.
It’s like starting a running total with no starting number. [].reduce((sum, n) => sum + n, 0) gives you 0, which is usually what people expect.
Fair
reduce is lovely until an empty array turns it into a surprise runtime error.
I just pass an explicit initial value every time now (0, '', []), because future-me will absolutely refactor something and trip over it.
I’m sympathetic to the “always pass an initial value” habit, but it can hide bugs too — returning 0 for “no data” is sometimes the wrong answer and you don’t notice until much later. I’ve started treating empty arrays as a case to handle explicitly so the behavior is intentional, not just “whatever identity value I picked. ”
Ngl I’ve been burned by this in a UI context where an empty list meant “don’t render the widget” but reduce(. . . , 0) quietly turned it into “render 0” and nobody noticed until QA. forcing an explicit empty-array branch feels way less like save scumming your data model.
:: Copyright KIRUPA 2024 //--