9

I put the following into the browser console:

0 === {} // false
{} === 0 // SyntaxError: expected expression, got '==='

Why is this?

Jack M
  • 4,769
  • 6
  • 43
  • 67
  • the operator of the first object is called and the second is passed to it, could be there a reason? – gkhaos Apr 11 '18 at 16:24
  • Exact duplicate: [Why {} == 1 entered in console throws error](https://stackoverflow.com/q/41302043/1048572), [“{} === null” throws syntax error in developer console](https://stackoverflow.com/q/20753091/1048572) – Bergi Apr 11 '18 at 16:28

1 Answers1

12

{} === 0 here {} is block statement not object literal.

But if you do say var a = {} === 0 it would work

var a = {} === 0

console.log(a);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • 3
    `{} === {}` is `false`. Why so? – 31piy Apr 11 '18 at 16:24
  • 1
    or even just `console.log( {} === 0 );` – Paul Apr 11 '18 at 16:26
  • 3
    @31piy `{}` creates a new object, so `{} === {}` creates two objects. Two distinct objects are not equal even if they have the same keys and values. `var a = {}; console.log( a === a );` is `true`, since only one object was created and you are comparing it to itself. – Paul Apr 11 '18 at 16:27
  • 2
    @Paulpro I think 31piy is referring to the fact that {}==={} is not a syntax error – alaboudi Apr 11 '18 at 16:28
  • @Paulpro I think he wanted to state other thing about the fact of block statement. – Ele Apr 11 '18 at 16:28
  • @gman it doesn't work with equivalence either. `{} == {}` is also false; – gforce301 Apr 11 '18 at 16:28
  • 1
    @alaboudi I think you're right about 31piy's question. I'll just leave what I wrote there though, in-case anyone else is wondering why the comparison is `false` and not `true`. – Paul Apr 11 '18 at 16:29
  • 4
    @31piy https://stackoverflow.com/q/14115902/1048572 – Bergi Apr 11 '18 at 16:30
  • @31piy Hmmm, `{} === {} // false` only in Chrome, but fails as expected in other browsers and parsers. I have checked acorn, esprima, babylon, typescript. – Yury Tarabanko Apr 11 '18 at 16:55
  • @31piy Actually typescript parses it. But it parses `{} === 1` as well – Yury Tarabanko Apr 11 '18 at 17:22