I was digging around the jQuery source code and I found that they use this little code snippet to detect if a JavaScript object is empty.
function isMyObjEmpty( obj ) {
var name;
for (name in obj ) {
return false;
}
return true;
}
Can someone explain to me why this works? I just don't understand why this would ever return true.
Having confirmed that the variable is an array, now we can check the length of the array using the Array. length property. If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.
The empty object is undefined, like this var empty_obj = {} . An undefined will be a false one.
keys() is a static method that returns an Array when we pass an object to it, which contains the property names (keys) belonging to that object. We can check whether the length of this array is 0 or higher - denoting whether any keys are present or not. If no keys are present, the object is empty: Object.
This uses a for... in
loop to iterate through the object's properties.
If the object has any property, it would enter the loop and return false
If the object has no properties, it would not enter the loop, and return true
.
Note that there exists a case where it does not work. for.. in
loops only go through enumerable
properties so technically an object can be non-empty and it would still return false. One can define a property to not be enumerable and trick this method. Here is the problematic case.
The correct thing to say is that this method checks if an object has any enumerable properties.
You can find the method's documentation here.
Description: Check to see if an object is empty (contains no enumerable properties).
I personally find it odd they would call that method isEmptyObject
. I think a better suited name would be hasNoEnumerableProperties
.
In newer implementations of JS one can use Object.getOwnPropertyNames
. getOwnPropertyNames
gets all the properties, enumerable or not.
You can implement isMyObjEmpty
with Object.getOwnPropertyNames(myObject).length===0
. This checks that the object has no properties, enumerable or not.
This however, does not check prototypical properties though. This might, or might not be desirable behavior, you can check the discussion I've had with theshadowmonkey about it. That could be easily solved by making a call to Object.getPrototypeOf
recursively and checking for properties across the prototypical chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With