Skip to main content

How do i check a js object is a empty object?

· One min read

One of the most common methods is to use Object.keys() judgment in modern browsers.

const empty = {};

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

You may be wondering why a constructor test was added?

We all know that there are nine built-in constructors in JS

new Object();
new String();
new Number();
new Boolean();
new Array();
new RegExp();
new Function();
new Date();

So we can create an object with new Object() function.

const obj = new Object();
Object.keys(obj).length === 0; // true

But,when we use other constructor to new an object, the result is also true. For example:

const obj = new String();
Object.keys(obj).length === 0; // true

To be more rigorous, if we want to check whether an object is empty, we can write it like this

function objectEmpty(value) {
value && Object.keys(value).length === 0 && value.constructor === Object;

We aslo can use Lodash 🤭

_.isEmpty({}); // true

That'all, thanks for reading!