How to check an object is empty in JavaScript?

Empty object check is really vital for writing clean code. We may run into unexpected issues in many cases if we don’t have a proper empty object check.

Following is the code to check empty objects in JavaScript:

// ES5 based solution
function isEmptyObject(obj) {
    return obj && Object.keys(obj).length === 0 && obj.constructor === Object;
}

In ES3, we could do the following to check an empty object in JavaScript:

// ES3 based solution
function isEmptyObject(obj) {
    for(const prop in obj) {
        if(obj.hasOwnProperty(prop)) {
            return false;
        }
    }
    return true;
}