I can understand [] ==! [] is correct, {} ==! {} is wrong, because toPrimitive([]) returns '' and toPrimitive({}) returns [object object], ''== 0, and [object object] != 0. Same reason, I also can understand ![] == {} returns false, but I wonder why {} == ![] report Uncaught SyntaxError: Unexpected token ==? Shouldn't the result also be false?
- 185
- 1
- 2
- 15
-
Because in the second case `{}` is a code block, not an object. – Federico klez Culloca Feb 27 '19 at 16:55
-
I would mark this as a duplicate but due to bad search capabilities im unable to find it. – Jonas Wilms Feb 27 '19 at 16:56
-
1I suppose this has to do with JS interpreting `{}` as an empty block rather than an empty object, by default. `({}) == ![]` should give the proper result. – Jeto Feb 27 '19 at 16:56
-
@quentin there are better dupes out there that explain the behaviour in the JS console. `{} == {}` would otherwise be a syntax error too – Jonas Wilms Feb 27 '19 at 17:01
1 Answers
The root of the problem is that {} got two meanings in JS:
{ let a = 1; } is a block statement
{ a: 1 } is an object literal expression
it will choose which to take wether it expects an expression or a statement. In your case, it is in a statement context, so {} is treated as a block statement, and therefore throws an error.
Now you could ask "Why does it accept {} == {} though?"
Well that's because your console sometimes evaluates the entered code as an expression and sometimes as a statement. I'ts rule is basically: If the code starts with { and ends with } it is parsed as an expression (it is wrapped in ( ). So when you type:
{ a: 1 }
that would actually be a SyntaxError in JS, as : is not defined inside a block statement, therefore the console is so nice to wrap it as:
({ a: 1})
the same happens with
{} == {}
// wrapped as
({} == {})
but this:
{} == []
does not fullfill the condition, the whole thing gets treated as a statement, {} is treated as a block statement.
- 132,000
- 20
- 149
- 151
