how to check whether a javascript object is empty?

JavaScript Add comments

== Option One ==

 
function isEmpty(ob){
   for(var i in ob){ return false;}
  return true;
}
 
isEmpty({a:1}) // false
isEmpty({}) // true

== Option Two ==

function isEmpty(o) {
  var o = {};
  for(var p in o) {
    if (o[p] != o.constructor.prototype[p])
      return false;
  }
  return true;
}

== Option Three ==

 
function isEmpty(ob){
   for(var i in ob){ if(ob.hasOwnProperty(i)){return false;}}
  return true;
}

== Option Four ==

what about this?

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

== Option five - Jquery ==

 
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

== References ==

* http://www.webdeveloper.com/forum/showthread.php?t=193474

* http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json

Similar question here about null object in javascript

* Check javascript object empty or null

Leave a Reply

Entries RSS