Why does [].reduce((acc, n) => acc + n) throw TypeError in JavaScript?
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 map, filter, and reduce Interview Questions in JavaScript
[1, NaN, NaN]. map passes (element, index, array) to the callback. parseInt takes (string, radix). So parseInt('2', 1) (radix 1 is invalid) is NaN, and parseInt('3', 2) (radix 2, '3' is invalid) is NaN. Fix with .map(s => parseInt(s, 10)).
map returns a new array (use for transformation). forEach returns undefined (use for side effects). Do not use map if you do not need the return value.
filter returns all matching elements as an array (possibly empty). find returns the first matching element (or undefined). Use filter for all matches; use find for one.
Still have questions?
Browse all our FAQs or reach out to our support team
