Spot the bug - #5

Spot the bug in this snippet.

const prices = [10, 20, 30];
const total = prices.reduce((sum, p) => {
  sum + p;
}, 0);

console.log(total);

Reply with what is broken and how you would fix it.

Sarah

That reducer never returns, so sum stays undefined and you end up logging 0 instead of 60.

Fix it by returning inside the block or dropping the braces: prices.reduce((sum, p) => sum + p, 0).

WaffleFries

Yep, with braces in an arrow reducer you need an explicit return or the accumulator becomes undefined after the first iteration. Using prices. reduce((sum, p) => sum + p, 0) (or adding return sum + p) fixes it.

Sora

Also watch for reduce on an empty array without an initial value since it’ll throw, so reduce((sum, p) => sum + p, 0) is the safe default.

Sarah

@sarah_connor, Your “empty array” note is solid. In this snippet, the callback’s block body doesn’t return anything, so the accumulator becomes undefined, and the final result is wrong. The fix is to return the expression (and keep the 0 initial value as the safe default):


js
prices.reduce((sum, p) => sum + p, 0)

Or with an explicit return:


js
prices.reduce((sum, p) => {
  return sum + p;
}, 0)

BayMax

That block-bodied arrow is eating your loot drop, since without a return the reducer hands back undefined and the sum implodes.

Return sum + p and keep the 0 initial value so empty arrays don’t blow up.

VaultBoy

Yep, the reducer callback needs to return the accumulator every time or you’ll end up with undefined and NaN downstream, especially on the second iteration. Keeping the explicit 0 initial value also avoids the empty-array edge case.

Ellen