Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript trivia: check for equality against the empty object

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?

like image 299
flybywire Avatar asked Feb 26 '10 09:02

flybywire


2 Answers

function isEmpty(o){
    for(var i in o){
        if(o.hasOwnProperty(i)){
            return false;
        }
    }
    return true;
}
like image 191
Li0liQ Avatar answered Oct 20 '22 10:10

Li0liQ


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

if (Object.keys(obj).length === 0) {
  // "empty" object
} else {
  // not empty
}
like image 24
Jan Hančič Avatar answered Oct 20 '22 11:10

Jan Hančič