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;
}
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;
}
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/
Another option is built into jQuery: jQuery.isEmptyObject(obj)
Edit: Interestingly, that implementation is the same as your code in the question.
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:
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?