LearnFrenzy
Sign in Take a free test

Array Methods · Find the Error · Question 13

Bug: the order total is a strange string Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links