Question 13
Back to Exercise
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
const orders = [{ amount: 100 }, { amount: 200 }, { amount: 300 }];
const total = orders.reduce((sum, o) => sum + o.amount);
console.log(total);
- A amount must be a string
- B reduce cannot read objects
- C The callback parameters are in the wrong order
- D Without an initial value the first accumulator is the first order object, so + turns it into a string – pass 0 as the initial value Correct
Correct Answer: Option D
The first call is { amount: 100 } + 200, which converts the object to "[object Object]" and concatenates from then on. reduce((sum, o) => sum + o.amount, 0) gives 600.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!