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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With