Functional Programming - Use the reduce Method to Analyze Data

Tell us what’s happening:

Hi guys,

Can you please tell me why curly braces are used in the code below?

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

const usersObj = users.reduce((obj, user) => {
  obj[user.name] = user.age;
  return obj;
}, {} /// curly bracket here

);

console.log(usersObj);

///The console would display the value { John: 34, Amy: 20, camperCat: 10 }.

The second argument of the reduce function describes the initial value of the accumulator, in this instance of obj.

Using an empty set of curly braces means that initial value of obj is an empty object. For each item of the array you add a property to obj and return its value to update the same object.

Hope that answers your question :slight_smile:

1 Like

Thank you buddy! It helped me

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