Determining whether a javascript object is empty

From Code Trash
Jump to: navigation, search

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 four - Jquery

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

References

Similar question here