How to test for an empty object in JavaScript

Today, I had to verify that an object was not empty.

Because JavaScript objects can be compared to reference in JavaScript, it is not possible to make an easy comparison like this.

const obj = {}

if (obj === {}) {
  //no
}

You can pass the object to the built in method  Object.keys()  to verify that the object constructor has been set to Object:

const obj = {}

Object.keys(obj).length === 0 && obj.constructor === Object

To avoid false positives, it is important to include the second check.

Exit mobile version