0

I was writing a script, and I had something like

var myObject = {};

if (myObject == {}){
    ...
}

I was surprised to find that this evaluated to false.

My own findings

Reading up on some of the funny querks javascript does, I found this article, which tells that {} will result in a "truthy" object in an if statement, for example

if ({}){ // true
    ...
}

Hm, well further ready discuesses String Equality, which for object comparison, says it will return true if they reference the same object. (Even {} === {} returns false)

The only reason I can think that is would return false is that the objects are technically at different memory address, and thus considered different objects.

Jacob Valenta
  • 6,659
  • 8
  • 31
  • 42
  • And your last sentence is the answer – Mchl Jul 01 '14 at 18:47
  • 1
    You've bolded the wrong word, which is the key to your misunderstanding. *"it will return true if they **reference** the same object"* should say *it will return true if they reference the **same** object.* – Jonathon Reinhart Jul 01 '14 at 18:48
  • You know this is not a question, right? In any case... I think a good explanation is that an object cannot equal another object. If you had 2 oranges that were the same, it doesn't mean they are the same orange. – durbnpoisn Jul 01 '14 at 18:48
  • Think of each instance of those brackets as "MyObject myObj = new MyObject();" in a static language. Easy way of thinking of it. – Katana314 Jul 01 '14 at 18:49
  • https://www.destroyallsoftware.com/talks/wat – Robert Levy Jul 01 '14 at 19:08
  • Dont' you remember, Jacob, was this post closed as duplicate before? I was pretty sure it was but strangely appears that it wasn't... – nicael Apr 02 '18 at 23:56

1 Answers1

10

Because every {} creates a unique object. You can't compare them that way.

nicael
  • 18,550
  • 13
  • 57
  • 90
  • 1
    you've beaten me to it :D – Desolator Jul 01 '14 at 18:48
  • 2
    I generally wouldn't recommend using `JSON.stringify` to compare objects. It will strip out functions and do other things to non-JSON types. Observe `JSON.stringify({r:/r/}) == JSON.stringify({r:{}})` – p.s.w.g Jul 01 '14 at 18:59
  • Using `.stringify` an unfortunate way to compare objects in general. I'd certainly not call it "right". In addition to what @p.s.w.g described, there's no guarantee that order of keys would be identical. – cookie monster Jul 01 '14 at 18:59
  • @p.s.w.g ok, i removed it. what would you suggest? – nicael Jul 01 '14 at 19:00
  • @nicael test the things you *really* care about. e.g. if you want to know that the object is empty, you might use `Object.keys({}).length == 0` – p.s.w.g Jul 01 '14 at 19:02
  • 1
    @RobinVanPersi if you want to have a nick like the footballer, you should use "Robin van Persie" :) – Maarten Bodewes Oct 19 '14 at 02:47