5

Is there a better way to check if an object is empty? I'm using this:

function isObjEmpty(obj)
{
    for (var p in obj) return false;
    return true;
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Rodrigo Manguinho
  • 1,411
  • 3
  • 21
  • 27
  • 1
    What do you consider "empty"? – Niko May 07 '12 at 13:36
  • Why to use [hasOwnProperty](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty) => ref: http://jsfiddle.net/v3Lyn/ – Yoshi May 07 '12 at 13:38
  • This question has nothing to do with JSON. – Felix Kling May 07 '12 at 13:51
  • possible duplicate of [How do I test for an empty Javascript object from JSON?](http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json) – Felix Kling May 07 '12 at 13:52

3 Answers3

10

If you're looking for a one-liner, consider Object.keys:

var isEmpty = !Object.keys(obj).length;

Your current method is dangerous, since it will always return false when Object.prototype has been extended: http://jsfiddle.net/Neppc/

Rob W
  • 341,306
  • 83
  • 791
  • 678
2

Another option is built into jQuery: jQuery.isEmptyObject(obj)

Edit: Interestingly, that implementation is the same as your code in the question.

Anna Brenden
  • 3,837
  • 2
  • 21
  • 19
0

Actually this is a very good way to check if an object is empty! And it is 10 times faster for exmpty objects than using Object.keys() as suggested above :)

Tested under Node, Chrom, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

See detailed testing results and test code at Is object empty?

Community
  • 1
  • 1
davidhadas
  • 2,333
  • 21
  • 17