Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 531
Web_Designer Avatar asked Dec 22 '25 12:12

Web_Designer


1 Answers

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)

like image 154
Felix Kling Avatar answered Dec 24 '25 02:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!