Search code examples
arraysobjectcomparison-operators

comparing objects in javascript


This is a general question about javascript object ontology and the way the === operator works.

start with an example:

var z = [1]; 
z === [1] // returns false.

Totally blew my mind. Why??

I guess it has to be that === is comparing the array as an object (i.e. by its object id or whatever), than by comparing the contents of the object--which would return true.

So what is a good way to compare the contents of an object like that?

You can force the issue by converting z.toString(), and comparing the result, but this seems crude.


Solution

  • You cannot compare two non-primitives values in javascript with == or === . The result is false, even if their structures and values are equals, because the comparison is not on the values but on the adress of the objects.

    Example
    
    z = [5];
    a = z;
    b = z;
    a === b; // true, because a and b linked to z.
    

    And to answer the question of "How to compare", you can effectively tostring, or make a loop on the two arrays...