How to check if an object is empty

JavaScript polyfill, by , Friday, March 7th, 2014

In JavaScript, there currently is not build in method to check if an object is empty, so you have to write your own. Fortunately this is fairly simple. One way that will work across all modern browsers is this

  1. var isEmpty = function (obj) {
  2. var key;
  3. for (key in obj) {
  4. if (obj.hasOwnProperty(key)) {
  5. return false;
  6. }
  7. }
  8. return true;
  9. };

While this works just fine, it is not very pretty. With ECMA-Script 5.1 however there has come a simpler and more elegant way of writing the same function;

  1. var isEmpty = function (obj) {
  2. return Object.keys(obj).length === 0;
  3. };

Or you could take advantage of another Object method available from this version of ECMA-Script;

  1. var isEmpty = function (obj) {
  2. return Object.getOwnPropertyNames(obj).length === 0;
  3. };

However for any of these two methods, if your audience uses older versions of IE (IE8 and older), this will not work. (see Kangax's compatibility table for more detail on browser compatibility)

Another simple way, that will work in all modern browsers that have JSON available is this;

  1. var isEmpty = function (obj) {
  2. return JSON.stringify(obj) === '{}';
  3. };

Which ever approach you choose think about your users and consider which environments they execute your code.