Experiences on the Front Lines of User Interfaces and Web Development

Detect if object is empty in JavaScript

I recently ran across a scenario where a function of mine was returning an Object (also known as a hash in other languages such as Ruby), and I wanted to check in the caller whether the returned Object was empty or not. I did not care what the contents were, just needed special handling for the empty case.

If you are already using jQuery, then this is a handy function that was added in 1.4 that I was unaware of! isEmptyObject
var myHash = { };
jQuery.isEmptyObject( myHash ); // true
myHash['foo'] = 'bar';
jQuery.isEmptyObject( myHash ); // false

It takes a single parameter, which is your Object, and returns true or false. It even takes into account "inherited" properties through the prototype object.
comments powered by Disqus