15

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?

2

5 Answers 5

21

You can also use Object.keys() to test if an object is "empty":

if (Object.keys(obj).length === 0) {
  // "empty" object
} else {
  // not empty
}
Sign up to request clarification or add additional context in comments.

2 Comments

that's the right answer. For who needs to have this working on IE8 check the es5-shim library.
This is 10 times slower than the (for...in) option - see stackoverflow.com/questions/4994201/is-object-empty?lq=1
18
function isEmpty(o){
    for(var i in o){
        if(o.hasOwnProperty(i)){
            return false;
        }
    }
    return true;
}

Comments

2

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

Comments

0

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.

Comments

0
javascript:
     cs = 'MTobj={   }; JSON.stringify(MTobj)=="{}"';
     alert(cs+'  is  '+eval(cs));
     cs = 'MTnot={a:2}; JSON.stringify(MTnot)=="{}"';
     alert(cs+'  is  '+eval(cs));

says

MTobj={   }; JSON.stringify(MTobj)=="{}"  is  true
MTnot={a:2}; JSON.stringify(MTnot)=="{}"  is  false

Caveat! Beware! there can be false positives!

javascript:
     cs = 'MTobj={ f:function(){} }; JSON.stringify(MTobj)=="{}"';
     alert(cs+'  is  '+eval(cs));
     alert("The answer is wrong!!\n\n"+
                    (cs="JSON.stringify({ f:function(){} })")+
                             "\n\n  returns\n\n"+eval(cs));

1 Comment

This is extremely unsafe and slow for no good reason to be unsafe and slow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.