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.
Arthur
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.
Arthur
In your snippet the reducer has braces but doesn’t return anything, so total ends up wrong (you’ll get 0 here because you passed an initial value of 0) — did you mean to return sum + p from the callback? I might be wrong here.
yep, with braces you need an explicit return or the reducer hands back undefined and the total goes sideways.
const total = prices.reduce((sum, p) => {
return sum + p;
}, 0);
Yeah, this is one of those arrow-function footguns: once you add {} you’ve got a block body, so you need an explicit return or your reducer returns undefined and the total goes off the rails.
const total = prices.reduce((sum, p) => {
return sum + p;
}, 0);
Or just skip the braces and let it implicitly return:
const total = prices.reduce((sum, p) => sum + p, 0);
I found a related kirupa. com article that can help you go deeper into this topic.
:: Copyright KIRUPA 2024 //--