4

Below is an example comparing two JavaScript objects but I am confused by the returned values.

var i=new Object()
var j=new Object()

i==j false

i!=j true

i>=j true

i<=j true

i>j false

i<j false

How are the values determined for the above? I am having trouble understanding.

2 Answers 2

7

Here are the reasons,

i==j false //Since both are referring two different objects

i!=j True  //Since both are referring two different objects

i>=j true  //For this, the both objects will be converted to primitive first,
           //so i.ToPrimitive() >= j.ToPrimitive() which will be 
           //evaluated to "[object Object]" >= "[object Object]" 
           //That is why result here is true.

i<=j true  //Similar to >= case

i>j false  //Similar to >= case

i<j false  //Similar to >= case

i<-j false //similar to >= case but before comparing "[object object]" will be negated 
           //and will become NaN. Comparing anything with NaN will be false 
           //as per the abstract equality comparison algorithm 

You mentioned i<-j will be evaluated to true. But that is wrong, it will be evaluated to false. See the reasons above.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks your answer,i typed wrong,it should be'i<=j',not 'i<-j'.since 'i<=j' is 'true' ,and 'i>=j' is 'true',so i should equal j,but not .
0

Because each time you create an object and assign it to a variable, the variable really has a reference to the new object. The references are not the same so they are not equal. You can see this by doing this:

var a = {};
var b = a;

a == b

Not very enlightening but if you think references, it all makes sense.

2 Comments

thanks your answer,i typed wrong symbol,now question have been updated.
@penggao which ones are unclear? My answer explains all except <= and >= and I would say those are just irrelevant -- there is no good answer to that when comparing objects so they are not logical to use. Edit: just realized > and < but illogical for same reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.