views:

99

answers:

3

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?

+3  A: 
function isEmpty(o){
    for(var i in o){
        if(o.hasOwnProperty(i)){
            return false;
        }
    }
    return true;
}
Li0liQ
You beat me by a couple of seconds.... :-)
The Elite Gentleman
http://api.jquery.com/jQuery.isEmptyObject/
Zac
A: 

There is not really a short way to determine if an object is empty has Javascript creates an object and internally adds constructor and prototype properties of Object automatically.

You can create your own isEmpty() method like this:

var obj={}
Object.prototype.isEmpty = function() {
    for (var prop in this) {
        if (this.hasOwnProperty(prop)) return false;
    }
    return true;
};
alert(obj.isEmpty());

So, if any object has any property, then the object is not empty else return true.

The Elite Gentleman
A: 

You can use this syntax

if (a.toSource() === "({})")

but this doesn't work in IE. As an alternative to the "toSource()" method encode to JSON of the ajax libraries can be used:

For example,

var o = {};
alert($.toJSON(o)=='{}'); // true

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

jquery + jquery.json

Vacheslav