8 ways to check JavaScript Object empty or not

JavaScript objects are a fundamental data structure in any web application. One of the common tasks when working with objects is to check if an object is empty or not. In this blog post, we will explore 8 different ways to check if a JavaScript object is empty.

1. Using the Object.keys()

This method returns an array of a given object’s own property names. If the array is empty, then the object is empty.

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

2. Using the for...in loop:

This loop iterates over the properties of an object. If the loop doesn’t execute even once, then the object is empty.

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

3. Using JSON.stringify()

This method converts a JavaScript value to a JSON string. If the JSON string is ‘{}’, then the object is empty.

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

4. Using Object.entries()

This method returns an array of a given object’s own enumerable property [key, value] pairs. If the array is empty, then the object is empty.

function isEmpty(obj) {
  return !Object.entries(obj).length;
}

5. Using Object.getOwnPropertyNames()

This method returns an array of a given object’s own enumerable property values. If the array is empty, then the object is empty.

function isEmpty(obj) {
  return !Object.getOwnPropertyNames(obj).length;
}

6. Using the Object.getOwnPropertySymbols()

This method returns an array of all symbol properties found directly upon the given object. If the array is empty, then the object is empty.

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

7. Using Object.values()

This method returns an array of a given object’s own enumerable property values. If the array is empty, then the object is empty.

function isEmpty(obj) {
  return !Object.values(obj).length;
}

8. Using Lodash or Underscore utility function

If you are using a library like Lodash or Underscore, you can use their utility function like _.isEmpty to check if the object is empty.

const isEmpty = (obj) => _.isEmpty(obj);

There are multiple ways to check if a JavaScript object is empty. You can use any of the above methods depending on the requirement. Keep in mind that these methods also work for arrays. As a tip, you can use the utility function provided by libraries like Lodash or Underscore to check if the object is empty.

Leave a Reply