SnipBits

How to check if an object is empty in JavaScript

The javascript Objects are compared by reference, that's why we cannot do a comparaison like this

let obj = {};

if (obj === {}) {
}

The Solution is to pass the built-in method Object.keys() and check if the Object Constructor is an Object like this

let obj = {};

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

The second check is to avoid the False Positives.


Maher Gallaoui

You like our Content? Follow us to stay up-to-date.