Javascript – Is an Object Empty?

To check if an object is empty in Javascript:

Object.getOwnPropertyNames(obj).length === 0;

Where obj is the object you’re testing e.g.:

var obj = {};
Object.getOwnPropertyNames(obj).length === 0; //true
obj = {'not' : 'empty'};
Object.getOwnPropertyNames(obj).length === 0; //false

Or to wrap it in a function:

function isEmpty(obj){
    return (Object.getOwnPropertyNames(obj).length === 0);

This only works in ECMAScript 5 compatible browsers, so is useful when developing mobile / desktop web apps.

4 thoughts on “Javascript – Is an Object Empty?

    • This code is not the same. This code does not check to see if the property is the object’s own property and not from the prototype chain. It will give false positives for objects with a modified prototype.

      var isEmpty = function(obj) {
        for (var key in obj)
            return false;
        return true;

      That’s why I like this approach in this article. It’s a lot cleaner. This one is backwards compatible though. I would expect the Object.getOwnPropertyNames method to be optimized by browsers, if not now then in the future, because it would be trivial for an engine to cache the ownProperties and this would make the code O(1)

  1. Pingback: Solution: How do I test for an empty Javascript object? #dev #it #computers | Technical information for you

Comments are closed.