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.
BayMax
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.
BayMax
Your reducer callback uses {} but never returns anything, so the accumulator becomes undefined and you end up with the initial value (or undefined depending on the setup) instead of the sum. Fix it by returning the expression: const total = prices. reduce((sum, p) => sum + p, 0); or, if you want braces: const total = prices. reduce((sum, p) => { return sum + p; }, 0);
okay so yeah, the {} is eating your return — arrow functions only do the implicit return when you don’t use braces, so your reducer callback is handing back undefined each time.
After that you’re basically accumulating undefined, so you’ll end up with NaN pretty fast. Either go expression-style:
const total = prices.reduce((sum, p) => sum + p, 0);
or keep the braces and be explicit:
const total = prices.reduce((sum, p) => {
return sum + p;
}, 0);
One extra wrinkle: if you remove the 0 initial value, this bug gets sneakier because the first sum will be 10, then your callback returns undefined, and the final total ends up undefined (not NaN). I found a related kirupa. com article that can help you go deeper into this topic:
Yep — the reducer callback never returns anything, and sum + p; doesn’t mutate sum, so sum becomes undefined on the next iteration and your total is wrong. Fix is to return the new accumulator:
const total = prices.reduce((sum, p) => sum + p, 0);
Kirupa has a good reduce refresher here: https://www.kirupa.com/javascript/using_array_reduce.htm
:: Copyright KIRUPA 2024 //--