Probably a duplicate of this question.
Silly javascript question: I want to check if an object is the emtpy object.
I call empty object the object that results from using the empty object literal, as in:
var o = {};
As expected, neither ==
nor ===
work, as the two following statements
alert({}=={});
alert({}==={});
give false.
Examples of expressions that do not evaluate to the empty object:
0
""
{a:"b"}
[]
new function(){}
So what is the shortest way to evaluate for the empty object?
function isEmpty(o){
for(var i in o){
if(o.hasOwnProperty(i)){
return false;
}
}
return true;
}
You can also use Object.keys() to test if an object is "empty":
if (Object.keys(obj).length === 0) {
// "empty" object
} else {
// not empty
}
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