Why do I get a syntax error if I run this in the c

2019-08-14 09:50发布

问题:

In the chromium console I run {} === {} and I get a Syntax error, unexpected '==='.

If I however wrap this in parens, like ({} === {}) then I get false, what I'd expect.

Is an object literal, in the first position, confused with a code block or something?

回答1:

Without a surrounding parenthesis, {} would be considered as an empty code block in javascript. = followed by a code block would be an invalid syntax. That is why you are seeing an error there.

If you wrap it inside of a parenthesis like ({} === {}), then it would be considered as an expression and it will be evaluated to false as both are referencing two different objects.

The following example may give you a clear picture about it,

{ var x = 5; console.log(x); } == 2
// will throw the same error that you are facing.