DEV Community

Discussion on: Compare objects in JS

nbilyk profile image
Nicholas Bilyk

" An object is not a data structure in which an order is defined, right?"
Yes and no. An object (any js object) has a list of keys that does have an explicit order. That order is first if the key can parse to a number, then the keys are ordered ascendingly, and then if the key cannot parse to a number, then the keys are sorted in the order they're inserted.
This is pretty specific to ecmascript/javascript, other languages have different rules for dynamic maps. In all languages however when creating equality rules for dynamic map-like structures, order isn't expected to matter for comparison. (Which is why stringify is the wrong choice for object comparison)

Example:

JSON.stringify({ '3': 'a', 'foo': 'd', '2': 'b', 'bar': 'e', '1': 'c' }) 

Becomes: {"1":"c","2":"b","3":"a","foo":"d","bar":"e"}
Enter fullscreen mode Exit fullscreen mode

Because those keys do have an order, if you used stringify as your comparison, {a: 1, b: 2} which you would expect to equal {b: 2, a: 1}, does not.