Javascript dot after curly bracket syntax error ?: {num: 1} .num

In Chrome devtools, enter the following: {num:1}.numgives a syntax error:

SyntaxError: Unexpected token .

... but entering this returns 1:

(function() {
    return {num:1}.num;
})();

Why am I getting a syntax error in the first example, but not the second?

+3
source share
1 answer

Since braces in this situation are ambiguous and are interpreted as a block statement , and not as an object literal. Sort of

{
    num: 1
}
.num

Where is num:interpreted as label .

You can use the grouping operator to force the construct to be interpreted as an expression:

({num: 1}).num

, return ( )

+5

All Articles