Posted By

satie83 on 06/13/13


Tagged

javascript Objects


Versions (?)

Javascript - How to know if an object is Empty


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/4994201/is-object-empty

Assuming that by empty means "has no properties of its own"

  1. // Speed up calls to hasOwnProperty
  2. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3.  
  4. function is_empty(obj) {
  5.  
  6. // null and undefined are empty
  7. if (obj == null) return true;
  8. // Assume if it has a length property with a non-zero value
  9. // that that property is correct.
  10. if (obj.length && obj.length > 0) return false;
  11. if (obj.length === 0) return true;
  12.  
  13. for (var key in obj) {
  14. if (hasOwnProperty.call(obj, key)) return false;
  15. }
  16.  
  17. return true;
  18. }

Report this snippet  

You need to login to post a comment.