0

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?

enter image description here

DangoSky
  • 185
  • 1
  • 2
  • 15

1 Answers1

0

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151