2

Possible Duplicate:
is object empty?

So let's var someObject = { }; how can i detect that object hasnt any properties and methods?

Community
  • 1
  • 1
Neir0
  • 12,849
  • 28
  • 83
  • 139

1 Answers1

5
function isEmpty(ob){
   for(var i in ob){ return false; }
   return true;
}

isEmpty({a:1}) // false
isEmpty({}) // true
xanatos
  • 109,618
  • 12
  • 197
  • 280
SShebly
  • 2,043
  • 1
  • 21
  • 29
  • That won't work if someone has added a method to `object.prototype`. Read here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ – xanatos Oct 21 '11 at 09:33
  • @xanatos: If "someone" adds to `Object.prototype`, you track it down, remove the offending code, then remove the offending developer. – user113716 Oct 21 '11 at 11:57
  • @Ӫ_._Ӫ In the real world, it is possible to have `object.prototype` extensions. There were even some quite famous libraries that did it (but I don't remember which ones were).... mmmmh an example in this bug report http://bugs.jquery.com/ticket/1529 and even older versions of the `prototype` library – xanatos Oct 21 '11 at 12:02
  • @xanatos: That jQuery bug is a great example. You're probably aware that the `json2` library (which was the cause of that bug) no longer extends `Object.prototype` as the original did. Same with `prototypejs`. They both removed the offending code. ;) – user113716 Oct 21 '11 at 12:15