Facebook Pixel
map, filter, and reduce Interview Questions in JavaScript

Why does [].reduce((acc, n) => acc + n) throw TypeError in JavaScript?

The answer

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.

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

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

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.
Please Login.
Please Login.