Find out how to check if a variable with an object is empty or not

How to check if JavaScript Object is empty

It can be difficult to check whether an object is empty in Javascript. With Arrays, you can easily check with myArray.length, but on the other hand, objects do not work that way.

We can create an Object by using the object literal syntax:

const emtpyObject = {};

Say you want to check if a value you have is equal to the empty object,

How can you do so?

Object.entries()

Use the Object.keys() function.

It returns an array of a given object’s enumerable property names, in the same order as we get with a normal loop.

It’s used like this:

Object.keys(emtpyObject);

If it returns an empty array, it means the object does not have any enumerable property name, which in turn means it’s empty.

Object.keys(emtpyObject).length === 0;

You should also make sure the object is actually an object, because the Array proto chains the Object, so it also have the keys method, by checking its constructor is the Object object:

emtpyObject.constructor === Object;

The best way to check if an object this empty is by using a utility function that implementes the hasOwnProperty() , this returns a boolean indicating whether the object has the specified property as its own property

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

So if you have an empty object, you can check whether it is empty by using the above function.

const myObj = {}; // Empty Object

if(isEmpty(myObj)) {
    // Object is empty
} else {
    // Object is NOT empty
}

Alternatively, you can write the isEmpty function on the Object prototype.

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

Then you can easily check if the object is empty like so.

const myObj = {
    test: 'Some Value'
};

if(myObj.isEmpty()) {
    // Object is empty
} else {
    // Object is NOT empty
}

Extending the Object prototype is not the best thing to do as it can cause some browser issues and other issues with certain frameworks. This is one of those utility functions that will always be useful, especially if you deal with a lot of objects on a daily basis.

Another alternative is to use Lodash, makes it simpler by providing the isEmpty() function:

import _ from 'lodash';

const myObj = {
    test: 'Some Value'
};

if(_.isEmpty(objectToCheck)) {
    // Object is empty
} else {
    // Object is NOT empty
}