Web_Designer
Web_Designer

Reputation: 74610

javascript dot after curly braces syntax error?: {num:1}.num

In Chrome's devtools typing this: {num:1}.num gives a syntax error:

SyntaxError: Unexpected token .

...but typing this returns 1:

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

Why do I get a syntax error in the first example but not the second?

Upvotes: 3

Views: 246

Answers (1)

Felix Kling
Felix Kling

Reputation: 816790

Because the braces are ambiguous in this situation, and interpreted as a block statement, not as object literal. Something like

{
    num: 1
}
.num

Where num: is interpreted as label.

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

({num: 1}).num

In the second case, the braces can only be an object literal because the return statement can only contain an expression (not a statement)

Upvotes: 5

Related Questions