DEV Community

loading...
Cover image for How do I test for an empty JavaScript object?

How do I test for an empty JavaScript object?

courseprobe profile image Course Probe ・2 min read

In this short tutorial we are going to explore some options and examples for testing Javascript objects for the empty condition.

There are times when working with objects the returned object will come as:

var object= {};
Enter fullscreen mode Exit fullscreen mode

This could happen when working with modules that pass data from a server to server, it might be the response of an API or backend service etc, so it’s handy to know in which way Javascript can check if object is empty.

Checking for empty objects in Javascript is easy, let’s jump into it.

Pre-ECMA 5:

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

  return JSON.stringify(obj) === JSON.stringify({});
}
Enter fullscreen mode Exit fullscreen mode

jQuery:

jQuery.isEmptyObject({}); // true
Enter fullscreen mode Exit fullscreen mode

lodash:

_.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

Underscore:

_.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

Hoek

Hoek.deepEqual({}, {}); // true
Enter fullscreen mode Exit fullscreen mode

ExtJS

Ext.Object.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

AngularJS (version 1)

angular.equals({}, {}); // true
Enter fullscreen mode Exit fullscreen mode

Ramda

R.isEmpty({}); // true
Enter fullscreen mode Exit fullscreen mode

Example 2:

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

    return true;
}
Enter fullscreen mode Exit fullscreen mode

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

function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
Enter fullscreen mode Exit fullscreen mode

Additional resources:

Get the book: Javascript snipets


Other Dev posts:

Discussion (1)

pic
Editor guide
Collapse
alfredosalzillo profile image
Alfredo Salzillo

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

It's not correct, Object.keys returns only enumerable properties of objects.

Object.keys({ [Symbol()]: '' }).lenght === 0; 
// this is true, but the object it's not empty
Enter fullscreen mode Exit fullscreen mode