16

It's commonly known that {} is shorter way to define an object like [] is for an array.

But now I am wondering why:

{} != ({})
  • {} evaluates to undefined
  • ({}) evaluates to "correct" Object

Why is JavaScript behaving like this ?

For example 1 equals to (1), so why {} not equals to ({}) ?

alex
  • 479,566
  • 201
  • 878
  • 984
Zaffy
  • 16,801
  • 8
  • 50
  • 77
  • 7
    `{} != ({})` is a syntax error. – the system Jan 02 '13 at 01:26
  • `1` and `{}` are quite different beasts. – Lightness Races in Orbit Jan 02 '13 at 01:30
  • By the way the same applies to arrays for similar reasons (because arrays are also objects): `[] != []` is true. – Stuart Jan 02 '13 at 01:33
  • Check out [Bizzare Javascript Behaviours](http://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the), with its [amazingly detailed answer](http://stackoverflow.com/questions/9032856/what-is-the-explanation-for-these-bizarre-javascript-behaviours-mentioned-in-the#answer-9033306). – Joseph Silber Jan 02 '13 at 01:37

2 Answers2

24
{} != ({})

This is a syntax error.

SyntaxError: Unexpected token !=

{} is ambigious like that. Is it an empty block, or an empty object literal? It's failing because a comparison operator can not follow a block.

Wrapping it with parenthesis makes the parser treat it as an expression. An expression can't contain a block, so it knows it's an object.

However, if you wrap that comparison in an expression...

({} != ({}))

...it's still true because variables which have an object assigned to them's values are a pointer to them and as a consequence, they are never copied around by their contents (though this is irrelevant to your example). Because of this, their pointer is always different and the comparison fails.

This also implies that comparing two variables which point to the same object will work as expected, as their pointers will be the same.

alex
  • 479,566
  • 201
  • 878
  • 984
  • Can you tell me what it does here `/*Instance methods*/ hasOwn = ({}).hasOwnProperty,` in the [jQuery source](http://code.jquery.com/jquery-1.11.0.js)? (Y) – loveNoHate Feb 14 '14 at 12:54
  • 1
    @dollarVar That could be its own question. It's the same thing, the authors want a reference to `Object.prototype.hasOwnProperty`, but are accessing it via an object literal. Due to ambiguity as mentioned in my answer, it must be wrapped in parenthesis, otherwise it's parsed as a block and there is no property lookups on blocks :) – alex Feb 14 '14 at 23:16
5

{} != {} is true because both {}'s are completely different objects. However, variables that are referencing the same object hold equality:

​var a = {},
    b = a;

assert( a == b )​
David G
  • 94,763
  • 41
  • 167
  • 253