How to check if an object is empty in JavaScript?

October 02, 2022 No comments js object empty javascript tips solutions

Introduction

In JavaScript, we may wish to check if an object is empty in JavaScript.

In this article, we'll learn how to check if an object is empty (do not confuse that with null|undefined).

How to check if an object is empty in JavaScript

There are several ways to check if an object is empty in JavaScript:

  • in Vanilla JS:
const isEmpty = (obj) => {
  for(var prop in obj) {
    if(Object.prototype.hasOwnProperty.call(obj, prop)) {
      return false;
    }
  }

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

console.log(isEmpty({})); // true
console.log(isEmpty({d: 'test'})); // false
  • 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

Conclusion

In this article, we presented several ways to check if an object is empty. Frameworks like Angular or jQuery have built-in solutions to do that verification. We can also use a solution in vanilla JS.

{{ message }}

{{ 'Comments are closed.' | trans }}