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
  • 756,363
  • 169
  • 1,062
  • 1,111
Rodrigo Manguinho
  • 1,411
  • 1
  • 20
  • 26
  • 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
  • 328,606
  • 78
  • 779
  • 666
2

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

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

Eric Brenden
  • 3,707
  • 2
  • 19
  • 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,253
  • 19
  • 16