In discussing syntax ambiguity, Crockford points out that in certain contexts, an open curly brace may be mistakenly recognized as the beginning of a block instead of an object literal.
For instance:
{"foo": "bar"} // SyntaxError
This would result in a syntax error because it is interpreted as a block with a string literal "foo" and an unexpected use of the token :
.
On the contrary, using parentheses, known as the grouping operator, eliminates this ambiguity since blocks are only expected in a statement context.
({"foo": "bar"})
Edit: @el.pescado raises an interesting question:
Can you explain why eval('{}') is undefined?
ECMAScript defines a Completion Specification Type to describe statement behaviors, consisting of triples like (type, value, target)
where type
can be normal
, break
, continue
, return
, or throw
.
For an empty block (Block : {}
), the explicit completion is:
Return (normal, empty, empty).
After executing code, the eval
function checks the result completion. If the type is normal
and value is empty
, it returns undefined
according to Step 7.
...
7- If result.type is normal and its completion value is empty, then return the value undefined.
...