What is the fastest way to check if an object is empty or not?
Is there a faster and better way than this:
function count_obj(obj){
var i = 0;
for(var key in obj){
++i;
}
return i;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’m assuming that by empty you mean “has no properties of its own”.
Examples:
If you only need to handle ECMAScript5 browsers, you can use
Object.getOwnPropertyNamesinstead of thehasOwnPropertyloop:This will ensure that even if the object only has non-enumerable properties
isEmptywill still give you the correct results.