0

I am trying to figure out what is the difference between;

let foo = ({ bar() {} });

and

let foo = { bar() {} };

I am not clear why code uses surrounding parentheses

const actions = ({
  setCounter ({ commit }, obj) {
    commit(MAIN_SET_COUNTER, obj)
  }
})

What I tried;

  • I assumed as IFEE but I could not understand how does it work

  • I assumed as a shorthand of function declaration

  • 5
    In the cases you show, nothing. See [Method definitions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), whether there are braces or not, doesn't matter here. – ASDFGerte Nov 11 '19 at 19:20
  • 1
    It's the same as the difference between `var foo = 1` and `var foo = (1)`. The `()` affect operator precedence, but there are no operators. – Quentin Nov 11 '19 at 19:22
  • They are not IIFE, but an object with a method property called bar – quirimmo Nov 11 '19 at 19:22
  • There are plenty of reasons, why unnecessary braces could be there. From code style, to automatically generated code, to some refactoring, which forgot to remove them. They are, in your examples, still unnecessary (but also not a mistake). – ASDFGerte Nov 11 '19 at 19:24
  • @ASDFGerte please post the *method definition* bit as an answer. – adiga Nov 11 '19 at 19:26
  • 1
    Related: [why are objects wrapped in parenthesis in JS?](https://stackoverflow.com/questions/12509311) – adiga Nov 11 '19 at 19:28

1 Answers1

1

The two first examples you show are semantically identical. In both cases, foo is assigned an object literal with a Method definition. The braces don't make a difference. As comments suggest, var foo = 1; is identical to var foo = (1);. In the third example, they are also not necessary. Note, that they also are not a mistake.

There are examples, where such braces make a difference, but they are not the ones you show. Some that come to mind:

  • Returning an object from an arrow function, shorthand version: let foo = () => ({});, differentiates from an empty code block.

  • Differentiating a code block from a stand-alone object, e.g. in the console: {} + []; vs ({}) + [];

  • IIFE, turning a function declaration statement into an expression: (function f(){})();, whereas function f(){}(); would result in an error.

ASDFGerte
  • 4,695
  • 6
  • 16
  • 33