}

JavaScript: How to know if and Object is empty?

Created:

Introduction

Some objects in javascript are easy to verify if they are empty. For example with an array you can use length and check how many items it contains. For any object there is no straigh forward way to do it, we need to add a function to check if the object is empty.

Checking if the object is empty

Vanilla Javascript pre-ECMAScript 5

We are going to create a new function and check if the object has any property set.

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

If you want to use it from any object you can use the Object.prototype and set the function isEmpty like this:

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

After execute the previous code, you can now use the isEmpty like this:

javascript if(myObj.isEmpty()) { console.log("Object empty"); }

Remeber that when you extend the prototype you could face issues with some browser or frameworks.

ECMAScript 5 support

With ECMAScript 5 you can use Object.keys():

javascript function isEmpty(obj) { return Object.keys(obj).length === 0; }

Jquery

javascript jQuery.isEmptyObject({}); // true

ExtJS

javascript Ext.Object.isEmpty({}); // true

AngularJS (version 1)

javascript angular.equals({}, {}); // true