How do I test for an empty JavaScript object?

falmp picture falmp · Mar 25, 2009 · Viewed 2.6M times · Source

After an AJAX request, sometimes my application may return an empty object, like:

var a = {};

How can I check whether that's the case?

Answer

Adam Zerner picture Adam Zerner · Aug 20, 2015

ECMA 5+:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
Object.keys(obj).length === 0 && obj.constructor === Object

Note, though, that this creates an unnecessary array (the return value of keys).

Pre-ECMA 5:

function isEmpty(obj) {
  for(var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
      return false;
    }
  }

  return JSON.stringify(obj) === JSON.stringify({});
}

jQuery:

jQuery.isEmptyObject({}); // true

lodash:

_.isEmpty({}); // true

Underscore:

_.isEmpty({}); // true

Hoek

Hoek.deepEqual({}, {}); // true

ExtJS

Ext.Object.isEmpty({}); // true

AngularJS (version 1)

angular.equals({}, {}); // true

Ramda

R.isEmpty({}); // true