Reduce Method in JavaScript

Hello!

I finished this challenge but I’m confuse why there is a 0 in the end of reduce method in variable sumOfAges and calculate correctly output 64. And I try to remove it in variable wrong and it’s output is [object Object]2010.

Can anyone explain why there is a zero there.


const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];

const sumOfAges = users.reduce((sum, user) => sum + user.age, 0);
console.log(sumOfAges); // 64

const wrong = users.reduce((sum, user) => sum + user.age);
console.log(wrong); // [object Object]2010
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

You can pass an initialValue as argument to reduce.

If it’s present or not the behavior changes:

When it’s present in the first iteration the currentValue will be the initialValue.
If not, it will be the first element of the array.

So in this case:

with initial value on the first iteration we have:
0, 34

without initial value we have:
{ name: 'John', age: 34 }, 20

Thus summing an object and a number will produce that weird result.

More info on this on MDN reduce page.
Hope it helps :slight_smile:

1 Like

Oh thank you it helps me to understand.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.