Javascript - How to know if an object is Empty


/ Published in: JavaScript

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


Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.