How to check if an Object is empty in JavaScript

When working with JavaScript, it’s common to need to determine if an object is lacking properties—that is, if it is empty. An empty object means that there are no key-value pairs inside it. This seemingly simple task can present itself in various scenarios, especially when dealing with data structures or API responses. In this article, we will explore several methods to reliably evaluate if an object is empty, considering performance, compatibility, and modern JavaScript practices.

Using Object.keys(), Object.values(), and Object.entries()

Object.keys()

const isEmpty = (obj) => Object.keys(obj).length === 0;

Object.keys() is a method that takes an object as an argument and returns an array of its own enumerable property names. If we get an empty array back, it means our object has no enumerable properties, which, by our criteria, makes it empty.

Object.values()

const isEmpty = (obj) => Object.values(obj).length === 0;

Similarly, Object.values() gives us an array of the object’s own enumerable property values. No values means an empty object.

Object.entries()

const isEmpty = (obj) => Object.entries(obj).length === 0;

And Object.entries() returns an array containing arrays of key-value pairs. If there are no key-value pairs, the object is empty.

Each of these methods provides a straightforward way to check for emptiness, but be aware that they don’t consider non-enumerable properties. Also, they are part of ECMAScript 2015 (ES6) and might not work in very old browsers.

The for...in Loop with Object.hasOwnProperty

For…in Loop

const isEmpty = (obj) => {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
};

Using a for...in loop allows us to iterate over the properties of an object. Paired with Object.hasOwnProperty, we can ensure that we’re only considering the object’s own properties and not properties inherited through its prototype chain. This method is solid, performance-wise, and works in older browsers.

JSON.stringify Method

Using Stringify

const isEmpty = (obj) => JSON.stringify(obj) === '{}';

For objects that don’t have any nested objects, JSON.stringify can quickly serialize an object to a string. An empty object would be serialized to the string “{}”. However, be cautious with this method as it won’t work correctly with objects containing methods or other non-serializable values.

jQuery, Underscore, and Lodash Libraries

Libraries

// jQuery
const isEmpty = (obj) => jQuery.isEmptyObject(obj);

// Underscore or Lodash
const isEmpty = (obj) => _.isEmpty(obj);

Although using libraries for such a simple task might seem overkill, some projects are already using these utilities, and they provide a convenient isEmpty function. These libraries take care of various edge cases and are extensively tested.

Backward Compatibility and Custom Solution

Custom Compatibility Function

const isEmpty = (obj) => {
  if (obj === null || obj === undefined || typeof obj !== 'object') {
    return true;
  }

  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }

  return true;
};

For those requiring a solution that works across a wide range of browsers, including outdated ones, writing a custom function that accounts for null, undefined, and provides type checking is a robust choice. The code snippet above offers an example of how to ensure cross-browser compatibility.

Throughout this article, we’ve delved into five different ways to check if an object is empty in JavaScript—using standard methods provided by modern JavaScript (Object.keys(), Object.values(), and Object.entries()), adopting a classic approach with for...in loop and Object.hasOwnProperty, leveraging JSON.stringify for simple objects, or relying on popular libraries such as jQuery, Underscore, or Lodash. Understanding these methods’ nuances, limitations, and applicability is essential for any JavaScript developer.

As you go forth with handling objects in your projects or applications, remember to choose the method that best fits your needs considering factors like compatibility, performance, and readability. Practice implementing these checks to become proficient at identifying empty objects in JavaScript.

By now, you should feel confident in knowing how to determine if an object is empty using JavaScript. If you’re looking for more tips or guidance on JavaScript best practices, consider checking out the Mozilla Developer Network Documentation for a comprehensive knowledge base.

Remember, efficient coding comes with understanding the tools at your disposal. Keep honing your skills, and you’ll be crafting reliable, performance-conscious code in no time.