Javascript – Is an Object Empty?

To check if an object is empty in Javascript:

  1.  
  2. Object.getOwnPropertyNames(obj).length === 0;
  3.  

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

  1.  
  2. var obj = {};
  3. Object.getOwnPropertyNames(obj).length === 0; //true
  4.  
  5. obj = {'not' : 'empty'};
  6. Object.getOwnPropertyNames(obj).length === 0; //false
  7.  

Or to wrap it in a function:

  1.  
  2. function isEmpty(obj){
  3. return (Object.getOwnPropertyNames(obj).length === 0);
  4. }
  5.  

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

3 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)
          if(obj.hasOwnProperty(key))
            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)

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>