How to test for empty objects in JavaScript

Today, I need to check whether an object is empty.

Since in JavaScript, objects are compared by reference, we cannot make simple comparisons like this:

const obj = {}

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

The solution is to pass the object to the built-in methodObject.keys()And check if the object constructor isObject:

const obj = {}

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

It is important to add a second check to avoid false positives.

Download mine for freeJavaScript beginner's manual

More js tutorials: