The following code shows three uses of JavaScript .reduce()
:
- add up a sum
- build an array
- 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);