Search code examples
javascriptarraysline-breaksarrow-functions

Can someone explain to me why this syntax using parentheses instead of curly brackets, adding comma and no more "return" in reduce method?


I have a quick question, which I think related to line break or something, but I could not find an answer or post about. Here's an example using reduce() method.

This is what I usually do or see:

const unique = ['a','b','c','a''a','a','b'];

unique.reduce((acc, val)=> {acc[val]=(acc[val]||0)+1; return acc;}, {}); //{ a: 4, b: 2, c: 1 }

However, we can also use this syntax: remove the curly brackets & return, use parentheses instead and add a , before acc. Can someone explain to me this syntax?

unique.reduce((acc, val)=> (acc[val]=(acc[val]||0)+1, acc), {}); // { a: 4, b: 2, c: 1 }



Solution

  • This is because comma operator is used in your example. From MDN:

    The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.

    In (acc[val]=(acc[val]||0)+1, acc) comma does exactly that, it does left part first then returns acc.

    Update: Replacing parentheses with curly brackets will not work, because it doesn't comply with JS arrow function syntax. From Arrow function article on MDN:

    if the body requires additional lines of processing, you'll need to re-introduce brackets PLUS the "return"

    so return is required with curly brackets, while with parentheses it's a concise arrow function which doesn't need return.