Example in Use the reduce Method to Analyze DataPassed

I have a question about the code below. I do not understand why an extra parameter is needed when adding sum + user.age. Is the zero the starting point for the accumulator? If so, shouldn’t it be possible to remove it and have reduce use the first age as the accumulator? Also, why is it there instead of passed as one of the arguments?

Your code so far

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);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

I’m not to sure, I wonder if it is to do with users being in an array and the ‘0’ allows the content inside to be acceseed

The accumulator is needed to keep track of the current sum value throughout iterations. And you’re correct, the 0 indicates that the initial value of sum should be 0, and if it’s omitted, the sum is initialised with the first value of the array. In this case, this would be an object with a name and age property, and the method would try to perform the addition Object + user.age, which is nonsensical. It can’t know that it should take the age property as initial value.

2 Likes

Its just how the reduce method is designed…reduce(callback {, optional initial value} ). It is passed as an argument to reduce, but not to the callback. Maybe the reason behind it, is the callback itself takes up to 4 parameters, adding the initial value as 5th would make combinations of the different parameters less comfortable.

1 Like

As said. If you didn’t initialize the starting value to a number sum would initially be an object.

If you just add the age properties of the two objects together and return a number then on the next iteration the accumulator would be a number and would not have an age property (if I understand correctly what you are proposing).

const sumOfAges = users.reduce((sum, user) => {
  console.log(typeof sum); // object, number
  console.log(typeof user); // object, object
  
  console.log(sum.age); // 34, undefined
  console.log(user.age); // 20, 10
  
  console.log(sum.age + user.age); // 54, NaN
  
  return sum.age + user.age;
});

console.log(sumOfAges); // NaN
const sumOfAges = users.reduce((sum, user) => {
  console.log(sum);
  console.log(user);
  
  return { age: sum.age + user.age };
}).age;

console.log(sumOfAges); // 64

From an API design perspective, I think it makes sense that the optional initialValue is on reduce.

1 Like

Thank you all for the explanations, I got it now :slight_smile:

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