Search code examples
javascriptnode.jsstringify

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?


Solution

  • 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.