Is object empty? [duplicate]

What is the fastest way to check if an object is empty or not?

Is there a faster and better way than this:

function count_obj(obj){
    var i = 0;
    for(var key in obj){
        ++i;
    }

    return i;
}

Solution 1:

For ECMAScript5 (not supported in all browsers yet though), you can use:

Object.keys(obj).length === 0

Solution 2:

I'm assuming that by empty you mean "has no properties of its own".

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

function isEmpty(obj) {

    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // If it isn't an object at this point
    // it is empty, but it can't be anything *but* empty
    // Is it empty?  Depends on your application.
    if (typeof obj !== "object") return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

Examples:

isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true

isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false

If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames instead of the hasOwnProperty loop:

if (Object.getOwnPropertyNames(obj).length > 0) return false;

This will ensure that even if the object only has non-enumerable properties isEmpty will still give you the correct results.

Solution 3:

EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.


Easy and cross-browser way is by using jQuery.isEmptyObject:

if ($.isEmptyObject(obj))
{
    // do something
}

More: http://api.jquery.com/jQuery.isEmptyObject/

You need jquery though.

Solution 4:

Underscore and lodash each have a convenient isEmpty() function, if you don't mind adding an extra library.

_.isEmpty({});