u936293
u936293

Reputation: 16264

Parentheses in an object literal

Are parentheses in an object literal simply the grouping operator?

node-stringify will convert:

 [ { a: 1 } ]

to the string:

 [({'a':1}),({'a':2})]

Can I take it that the parentheses here have no impact to the data, ie it is totally the same even if the parentheses are absent?

Upvotes: 3

Views: 1263

Answers (3)

rgthree
rgthree

Reputation: 7273

The parenthesis are so the the result works with eval which, specifically, is how they test the functionality in the spec file.

On the GitHub page itself they state:

// The parenthesis is to make the result work with `eval`
console.assert(stringify({a: 1, b: 2}) === '({a:1,b:2})');

To explain further: Normally, eval interprets the { token as the start of a block, not as the start of an object literal. By wrapping the object in parentheses eval interprets it as a full expression and, thusly, returns the parsed object literal correctly, which is important for the authors tests and otherwise not important for other implementations (as you've already noticed).

Upvotes: 1

gyre
gyre

Reputation: 16777

Yes, (...) in this case is simply being used for grouping an expression. Omitting the parentheses would have no impact on your current data structure.

Parentheses can become more useful in situations where object literals might be interpreted as a block statement instead, e.g. when evaluating an expression in the developer console or when used inside ES6 Arrow functions:

const first = () => {a: 1}
const second = () => ({a: 1})

console.log(first()) //=> undefined
console.log(second()) //=> {a: 1}

I suspect this is why node-stringify has nominated to include them in its output ― to avoid ambiguity wherever possible.

Upvotes: 4

Harry Sadler
Harry Sadler

Reputation: 324

I'm not sure why node-stringify is putting parentheses around the objects like you describe. But yes, the data structure is the same with or without the parentheses.

Here's an example of JSON.stringify in the browser:

var data = [
  {
    'a':1
  },
  {
    'a':2
  }
];

var stringified = JSON.stringify(data);

console.log(stringified);

Upvotes: 0

Related Questions