How to test for an empty javascript object

Hi everybody! I’ve just had a discussion of how to test for an emtpy javascript object. As a result, I have several code snippets and I want to share them with You.

Problem

alert({}==null); // false
alert({}=={}); // false
alert({}=={}); // false
alert({}==0); // false
alert({}==""); // false
alert({}==[]); // false
// etc :)

So, none of the expressions above can check for an empty javascript object.

Pure javascript solution

function empty(o) {
    for(var i in o) 
        if(o.hasOwnProperty(i))
            return false;
 
    return true;
}
object.hasOwnProperty(property) Returns a boolean indicating whether the object has the specified property. This method does not check down the object’s prototype chain.

Learn details of hasOwnProperty here at developer.mozilla.org.

JQuery + JQuery.JSON solution

var o = {};
alert($.toJSON(o)=='{}'); // true
 
var o = {a:1};
alert($.toJSON(o)=='{}'); // false

The code above simply converts an object to JSON string.

Your way

Well, if You have Your way of checking for an empty javascript object I am waiting Your comments! Thanks in advance!

Links

hasOwnProperty documentation

JQuery JavaScript Library

jquery-json plugin for JQuery

Leave a Reply

Search
Categories
Advertisement
Artisteer - Web Design Generator