3765
votes

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

var a = {};

How can I check whether that's the case?

30
Do you use JSON.js script? Or any other JSON library. Then you can use JSON.encode() function to convert var to string and then test it.Thevs
Just check for if (Object.keys(obj).length === 0) { // handle empty obj }Gabriel Petersson
@GabrielPetersson Please never provide solutions as comments. Your comment is a violation of this Q&A's very clear/simple page design. Resolving advice is to be posted as an answer. Comments under the question should ask the OP for clarification or offer non-resolving insights. meta.stackexchange.com/a/296481/352329mickmackusa

30 Answers

6484
votes

ECMA 5+:

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // 👈 null and undefined 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
1018
votes

If ECMAScript 5 support is available, you can use Object.keys():

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}

For ES3 and older, there's no easy way to do this. You'll have to loop over the properties explicitly:

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

    return true;
}
584
votes

For those of you who have the same problem but use jQuery, you can use jQuery.isEmptyObject.

344
votes

This is my preferred solution:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty
219
votes

You can use Underscore.js.

_.isEmpty({}); // true
179
votes

Performance

Today 2020.01.17 I perform tests on macOS HighSierra 10.13.6 on Chrome v79.0, Safari v13.0.4 and Firefox v72.0, for chosen solutions.

Conclusions

  • solutions based on for-in (A,J,L,M) are fastest
  • solutions based on JSON.stringify (B,K) are slow
  • surprisingly also solution based on Object (N) is slow

enter image description here

Details

There are 15 solutions presented in the snippet below. If you want to run a performance test on your machine click HERE. This link was updated 2021.07.08 but tests oryginaly was performed here - and results in table above came from there (but now it looks like that service not longer works).

var log = (s,f) => console.log(`${s} --> {}:${f({})}  {k:2}:${f({k:2})}`);

function A(obj) {
  for(var i in obj) return false; 
  return true;
}

function B(obj) {
  return JSON.stringify(obj) === '{}';
}

function C(obj) {
  return Object.keys(obj).length === 0;
}

function D(obj) {
  return Object.entries(obj).length === 0;
}

function E(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

function F(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

function G(obj) {
  return typeof obj === "undefined" || !Boolean(Object.keys(obj)[0]);
}

function H(obj) {
  return Object.entries(obj).length === 0 && obj.constructor === Object;
}

function I(obj) {
  return Object.values( obj  ).every( val => typeof val === "undefined" );
}

function J(obj) {
  for (const key in obj) {
    if (hasOwnProperty.call(obj, key)) {
      return false
    }
  }
  return true;
}

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

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

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

  return true;
}

function M(obj) {
  for (var k in obj)
  { 
    if ( obj.hasOwnProperty(k) )
    { 
      return false;
    } 
  }
  return true; 
}

function N(obj) {
  return Object.getOwnPropertyNames(obj).length === 0 &&
  Object.getOwnPropertySymbols(obj).length === 0 &&
  Object.getPrototypeOf(obj) === Object.prototype; 
}

function O(obj) {
  return !(Object.getOwnPropertyNames != undefined ? Object.getOwnPropertyNames(obj).length != 0 : (function(){for(var key in obj) break; return (key != null) && (key != undefined);})())
}

log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
log('O',O);

enter image description here

If my answer helped you can buy me a coffee

123
votes
if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

see http://bencollier.net/2011/04/javascript-is-an-object-empty/

93
votes

How about using JSON.stringify? It is almost available in all modern browsers.

function isEmptyObject(obj){
    return JSON.stringify(obj) === '{}';
}
62
votes

Old question, but just had the issue. Including JQuery is not really a good idea if your only purpose is to check if the object is not empty. Instead, just deep into JQuery's code, and you will get the answer:

function isEmptyObject(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}
61
votes

I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

And what I did was, used the following condition, and it worked for me.

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

Check out this JSFiddle

43
votes

There is a simple way if you are on a newer browser. Object.keys(obj).length == 0

42
votes

Using Object.keys(obj).length (as suggested above for ECMA 5+) is 10 times slower for empty objects! keep with the old school (for...in) option.

Tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not suprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

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

See detailed testing results and test code at Is object empty?

35
votes

You could check for the count of the Object keys:

if (Object.keys(a).length > 0) {
    // not empty
}
29
votes
  1. Just a workaround. Can your server generate some special property in case of no data?

    For example:

    var a = {empty:true};
    

    Then you can easily check it in your AJAX callback code.

  2. Another way to check it:

    if (a.toSource() === "({})")  // then 'a' is empty
    

EDIT: If you use any JSON library (f.e. JSON.js) then you may try JSON.encode() function and test the result against empty value string.

25
votes

I've created a complete function to determine if object is empty.

It uses Object.keys from ECMAScript 5 (ES5) functionality if possible to achieve the best performance (see compatibility table) and fallbacks to the most compatible approach for older engines (browsers).

Solution

/**
 * Returns true if specified object has no properties,
 * false otherwise.
 *
 * @param {object} object
 * @returns {boolean}
 */
function isObjectEmpty(object)
{
    if ('object' !== typeof object) {
        throw new Error('Object must be specified.');
    }

    if (null === object) {
        return true;
    }

    if ('undefined' !== Object.keys) {
        // Using ECMAScript 5 feature.
        return (0 === Object.keys(object).length);
    } else {
        // Using legacy compatibility mode.
        for (var key in object) {
            if (object.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }
}

Here's the Gist for this code.

And here's the JSFiddle with demonstration and a simple test.

I hope it will help someone. Cheers!

25
votes

As per the ES2017 specification on Object.entries(), the check is simple using any modern browser--

Object.entries({}).length === 0
22
votes

My take:

function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}

var a = {
  a: 1,
  b: 2
}
var b = {}

console.log(isEmpty(a)); // false
console.log(isEmpty(b)); // true

Just, I don't think all browsers implement Object.keys() currently.

21
votes

I am using this.

function isObjectEmpty(object) {
  var isEmpty = true;
  for (keys in object) {
     isEmpty = false;
     break; // exiting since we found that the object is not empty
  }
  return isEmpty;
}

Eg:

var myObject = {}; // Object is empty
var isEmpty  = isObjectEmpty(myObject); // will return true;

// populating the object
myObject = {"name":"John Smith","Address":"Kochi, Kerala"}; 

// check if the object is empty
isEmpty  = isObjectEmpty(myObject); // will return false;

from here

Update

OR

you can use the jQuery implementation of isEmptyObject

function isEmptyObject(obj) {
  var name;
  for (name in obj) {
    return false;
  }
  return true;
}
17
votes
function isEmpty(obj) {
  for(var i in obj) { return false; }
  return true;
}
16
votes

The following example show how to test if a JavaScript object is empty, if by empty we means has no own properties to it.

The script works on ES6.

const isEmpty = (obj) => {
    if (obj === null ||
        obj === undefined ||
        Array.isArray(obj) ||
        typeof obj !== 'object'
    ) {
        return true;
    }
    return Object.getOwnPropertyNames(obj).length === 0;
};
console.clear();
console.log('-----');
console.log(isEmpty(''));           // true
console.log(isEmpty(33));           // true
console.log(isEmpty([]));           // true
console.log(isEmpty({}));           // true
console.log(isEmpty({ length: 0, custom_property: [] })); // false
console.log('-----');
console.log(isEmpty('Hello'));      // true
console.log(isEmpty([1, 2, 3]));    // true
console.log(isEmpty({ test: 1 }));  // false
console.log(isEmpty({ length: 3, custom_property: [1, 2, 3] })); // false
console.log('-----');
console.log(isEmpty(new Date()));   // true
console.log(isEmpty(Infinity));     // true
console.log(isEmpty(null));         // true
console.log(isEmpty(undefined));    // true
13
votes

jQuery have special function isEmptyObject() for this case:

jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false

Read more on http://api.jquery.com/jQuery.isEmptyObject/

13
votes

I would go for checking if it has at least one key. That would suffice to tell me that it's not empty.

Boolean(Object.keys(obj || {})[0]) // obj || {} checks for undefined
12
votes

Under the hood all empty check methods in all libraries use object keys checking logic. Its an odd way to make it understandable, which you can put in a method, Described here.

for(key in obj){
   //your work here.
 break;
}

Which has evolved in ES5, now put simply you can check the object's keys length, using Object.Keys method which takes your object as it's parameter:

if(Object.keys(obj).length > 0){
 //do your work here
}

Or if you are using Lodash (you must be) then.

 _.isEmpty(obj) //==true or false
11
votes


you can use this simple code that did not use jQuery or other libraries

var a=({});

//check is an empty object
if(JSON.stringify(a)=='{}') {
    alert('it is empty');
} else {
    alert('it is not empty');
}

JSON class and it's functions (parse and stringify) are very usefull but has some problems with IE7 that you can fix it with this simple code http://www.json.org/js.html.

Other Simple Way (simplest Way) :
you can use this way without using jQuery or JSON object.

var a=({});

function isEmptyObject(obj) {
    if(typeof obj!='object') {
        //it is not object, so is not empty
        return false;
    } else {
        var x,i=0;
        for(x in obj) {
            i++;
        }
        if(i>0) {
            //this object has some properties or methods
            return false;
        } else {
            //this object has not any property or method
            return true;
        }
    }
}

alert(isEmptyObject(a));    //true is alerted
11
votes

Best way that I found:

function isEmpty(obj)
{
    if (!obj)
    {
        return true;
    }

    if (!(typeof(obj) === 'number') && !Object.keys(obj).length)
    {
        return true;
    }

    return false;
}

Works for:

    t1: {} -> true
    t2: {0:1} -: false
    t3: [] -> true
    t4: [2] -> false
    t5: null -> true
    t6: undefined -> true
    t7: "" -> true
    t8: "a" -> false
    t9: 0 -> true
    t10: 1 -> false
9
votes

If jQuery and the web browser is not available, there is also an isEmpty function in underscore.js.

_.isEmpty({}) // returns true

Additionally, it does not assume the input parameter to be an object. For a list or string or undefined, it will also turn the correct answer.

9
votes

The correct answer is:

const isEmptyObject = obj =>
  Object.getOwnPropertyNames(obj).length === 0 &&
  Object.getOwnPropertySymbols(obj).length === 0 &&
  Object.getPrototypeOf(obj) === Object.prototype;

This checks that:

  • The object has no own properties (regardless of enumerability).
  • The object has no own property symbols.
  • The object's prototype is exactly Object.prototype.

In other words, the object is indistinguishable from one created with {}.

9
votes

A simpler solution: var a = {};
Case a is empty: !Object.keys(a).length returns true.

8
votes

In addition to Thevs answer:

var o = {};
alert($.toJSON(o)=='{}'); // true

var o = {a:1};
alert($.toJSON(o)=='{}'); // false

it's jquery + jquery.json

8
votes

Caveat! Beware of JSON's limitiations.

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

displays

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}