Skip to content

Check empty object JavaScript | Example code

You can use the plain vanilla JS Object keys() method to Check empty objects in JavaScript. For older browser support, install the Lodash library and use their “isEmpty” method.

Object.keys(data).length === 0 && data.constructor === Object

//Lodash for Older Browser
_.isEmpty(empty)

OR

// because Object.keys(new Date()).length === 0;
// we have to do some additional check
obj // 👈 null and undefined check
&& Object.keys(obj).length === 0
&& Object.getPrototypeOf(obj) === Object.prototype

Check empty object JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    const obj = {};

    if (Object.keys(obj).length === 0 && obj.constructor === Object){
      console.log("Object is empty", true)
    }
    
  </script>
</body>
</html>

Output:

Check empty object JavaScript

Other options

Pre-ECMA 5:

function isEmpty(obj) {
  for(var prop in obj) {
    if(Object.prototype.hasOwnProperty.call(obj, 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

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading