Categories
JavaScript

How to check if JavaScript object is empty?

One of the main strengths of JavaScript is the Object data type. When we work with objects often we will need to check if the object is empty. We can not do it, as we do with some other data types, because objects are compared by reference.

let obj = {};

if (obj === {}) {
    //This will not work
}

if (obj === '') {
    //This will not work
}

if (obj === 0) {
    //This will not work
}

if (obj.length === 0) {
    //This will not work
}

There are several ways we can find out if object is empty. The easiest way is just to pass our object to Object built-in method called keys and then use JavaScript length property. Also we need to check if object constructor is Object. And we do this to avoid false positives.

const boj = {}

if(Object.keys(obj).length === 0 && obj.constructor === Object) {
    //This will do
}

The other way of doing this includes either creating a function or even adding this function to Object prototype, which is not recommended.

let obj = {}

function isEmpty(obj) {
    for(var key in obj) {
        if(obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

if (isEmpty(obj)) {
    //This will execute if Object is empty
}

We created a function that iterates through object and checks for hasOwnProperty(). The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it), according to MDN.

As we mentioned earlier, we can also add this function to Object prototype.

Object.prototype.isEmpty = function() {
    for(var key in this) {
        if(this.hasOwnProperty(key))
            return false;
    }
    return true;
}

let obj = {};
if(obj.isEmpty()) {
    // This code will be executed if object is empty
} else {
    // This code will be executed if object is not empty
}

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like How to terminate function in JavaScript?