DEV Community

Cover image for Object Equality in JavaScript
Raz Chiriac
Raz Chiriac

Posted on

Object Equality in JavaScript

Howdy! Here’s a simple way to check for object equality.

Let’s say we have two objects:

const carA = {make: 'Ford', model: 'F150', year: '2018', color: 'white'}
const carB = {make: 'Ford', model: 'F150', year: '2018', color: 'white'}

We can see that carA is the same as carB. So we would expect carA === carB to return true but it does not. This is because JavaScript checks for equality on non-primitive types like Objects, Arrays and Dates by reference. This means, JavaScript checks if the two objects point to the same place in memory, not if they have the same key-value pairs.

One way to check for key-value equality of two objects, without the use of an external library or much coding is by converting the objects to strings using JSON.stringify() .

carA == carB // => false
carA === carB // => false

JSON.stringify(carA) === JSON.stringify(carB) // => true

Keep in mind that this approach only works if the key-value pairs are in the same order on both objects. We could go into sorting object entries by key and other approaches in future posts.

Cheers! 🫖

Top comments (0)