2

I know that we cann't directly compare a object whether equals the other. {} == {} will return false.

var b = {};
b === Object(b); //true
b === Object({}); //false

however, the codes above confuses me, why b === Object({}) return false? can someone explains it?

Tinple
  • 1,261
  • 1
  • 11
  • 11
  • well as a c# dev i can tell you that even if the objects are identical if they are separate then they have different references thus will never be equal. – Wobbles Jul 27 '14 at 12:20
  • 1
    Because when you do `Object({})` you are declaring a new instance of `{}` - it's not the same instance as `b`. – Ant P Jul 27 '14 at 12:21
  • `b === {}` will return `false` as well. What do you need the `Object` function for? Or is your confusion about that? – Bergi Jul 27 '14 at 12:40
  • @Bergi - The OP seems to be aware that two objects are never equal, it looks to me like the confusion is about the Object constructor, and why it returns what it does ? – adeneo Jul 27 '14 at 13:28

2 Answers2

3

It's actually in the documentation

The Object constructor creates an object wrapper for the given value. If the value is null or undefined, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

As you already know, two objects are never the same

{} == {} // false

But when you pass an object to the Object constructor, it returns that exact same object, not a new one.

var b = {};
b === Object(b); //true

Here you pass the same object to the Object constructor that you're comparing agains, and the Object constructor will return that same object, and comparing an object against itself returns true. In other words, the above is the same as b === b.
Moving on to this

b === Object({}); //false 

here you're passing in an empty new object, that object will be returned, but it will never be the same object as b, and two different objects are never equal, hence false

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

Whenever you will say {} ot Object({}) everytime you are creating a new instance of Object {}.

So

b={}; // instance one
Object({}); //instance two

b===Object({}) is same as b==={}. Both will return false.

That's why both have different references.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68