0

The following code shows three uses of JavaScript .reduce():

  1. add up a sum
  2. build an array
  3. build a JavaScript object

How does one understand the added parentheses around the braces in the third example? Are they just there so that the object-braces are not interpreted as function-braces? Or do they have some other purpose?

Is there another way to write the third example so that this syntax is more explicit, e.g. could one build the JavaScript object within a multiline function somehow?

const languages = ['french', 'french', 'spanish', 'polish', 'spanish', 'german', 'spanish', 'polish', 'spanish', 'spanish', 'french', 'spanish', 'english', 'french', 'spanish', 'english', 'french', 'english'];

// 1. iterating while adding a sum
const sum = languages.reduce((acc, language) => {
    acc++;
    return acc;
}, 0);
console.log(`There are ${sum} entries.`);

// 2. iterating while building an array
const initials = languages.reduce((acc, language) => {
    acc.push(language.substring(0, 1));
    return acc;
}, []);
console.log(initials);

// 3. iterating while building a JavaScript object
const totals = languages.reduce((acc, language) => ({
    ...acc,
    [language]: acc[language] ? acc[language] + 1 : 1
}), {});
console.log(totals);
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

1 Answers1

3

Yes they are there to prevent the brackets from being readed as frunction-braces because:

.reduce((acc,language) => acc)

Without curly braces the arrow function will return whats on the right side. Its the equivalent to this here:

.reduce((acc,language) => { return acc })

In case you want to return an object {} you cant simply use curly braces they would be interpreted as function-braces so you would need to wrap them in parenthesis

.reduce((acc,language) => ({...acc})

And this is the equivalent to:

.reduce((acc,langauge) => {
   return {...acc};
})
bill.gates
  • 14,145
  • 3
  • 19
  • 47