To check if an object is empty in Javascript:
Object.getOwnPropertyNames(obj).length === 0;
Where obj is the object you’re testing e.g.:
var obj = {};
Object.getOwnPropertyNames(obj).length === 0; //true
obj = {'not' : 'empty'};
Object.getOwnPropertyNames(obj).length === 0; //false
Or to wrap it in a function:
function isEmpty(obj){
return (Object.getOwnPropertyNames(obj).length === 0);
}
This only works in ECMAScript 5 compatible browsers, so is useful when developing mobile / desktop web apps.
If you wrap it in a function you can just use:
var isEmpty = function(obj) {
for (var key in obj) return false; return true;
}
The performance test speaks for itself: http://jsperf.com/for-in-vs-object-getownpropertynames
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.
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)
Agreed, +1 for native methods (i.e. getOwnPropertyNames);