14

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
}
2
18
function isEmpty(o){
    for(var i in o){
        if(o.hasOwnProperty(i)){
            return false;
        }
    }
    return true;
}
0
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

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.

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
  • This is extremely unsafe and slow for no good reason to be unsafe and slow.
    – Alex Bausk
    Commented Apr 2, 2018 at 10:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.