During some tests I found at least 3 ways to check if object “is empty”. I mean, do not contains any enumerable properties. Assuming we have an object:

<code lang="javascript">var obj = {};</code>

Then we can use:

if(JSON.stringify(obj) == '{}'){
    // object is "empty"
}

or

if(Object.keys(obj).length == 0){
    // object is "empty"
}

or

var isObjectEmpty = function (obj) {
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            return false;
        }
    }
    return true;
};

if(isObjectEmpty(obj)){
    // object is "empty"
}

Note: window.JSON method is not available in IE7 and lower natively. Also, Object.keys doesn’t work in IE < 9.

Comments

You can leave a response, or trackback from your own site.

Before you add comment see for rules.

Leave a Reply

Your email address will not be published. Required fields are marked *

8n6q2h