Empty JS Object

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

function isObjEmpty(obj)
{
    for (var p in obj) return false;
    return true;
}
+5
source share
3 answers

If you are looking for one liner, consider Object.keys:

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

Your current method is dangerous, as it will always return false if Object.prototypeextended: http://jsfiddle.net/Neppc/

+10
source

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

Edit: Interestingly, this implementation matches your code in the question.

+2
source

, ! 10 exmpty, Object.keys(), :)

Node, Chrom, Firefox IE 9, , :

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

Bottom line effect, 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 test results and test code for Is the object empty?

0
source

All Articles