0

According to Airbnb Javascript Style Guide, a pair of parentheses should be added to wrap the braces. But why?

// good
[1, 2, 3].map((number, index) => ({
  [index]: number,
}));

Is there anything wrong if I code without those parentheses? I mean just return the object is easier to read.

// anything wrong with this?
[1, 2, 3].map((number, index) => {
  return {[index]: number};
});
shen
  • 933
  • 10
  • 19
  • 1
    see how you are inside a function and not returning anything? This is the reason for the double. – Michael Mano Mar 29 '22 at 22:33
  • Sorry I didn't edit the code correctly. Now it fixed. – shen Mar 29 '22 at 22:34
  • 3
    Did you mean to link to https://github.com/airbnb/javascript#arrows--implicit-return? That tells you why it's preferred. Evidently the authors disagree with you about which is easier to read. – jonrsharpe Mar 29 '22 at 22:37
  • 1
    @jonrsharpe That rule explicitly lists OP's problem syntax as *good*. It's rather [this rule](https://eslint.org/docs/rules/arrow-body-style). – connexo Mar 29 '22 at 22:39
  • @connexo yes, that's the underlying ESLint rule; I linked to where in the relevant style guide it's applied, which also says why. – jonrsharpe Mar 29 '22 at 22:41
  • Now I kind of understand the purpose of `()` here is to keep the literal object `{[index]: number}` being an expression. – shen Mar 29 '22 at 22:45
  • Thx guys, I get the point now. But every time I saw code like this, it still takes a while for me to realize that ok `foo.map((number, index) => ({ [index]: number, }));` is a returned object literal wrapped as an expression. – shen Mar 29 '22 at 22:53
  • 1
    They both do the same thing in the use case you've provided. Just a matter of style choice :) I use both for returning objects – mstephen19 Mar 29 '22 at 22:54
  • yeah, both are right. In order to omit a `return`, they choose to add parentheses in parentheses. – shen Mar 29 '22 at 23:02

0 Answers0