How to check if an object is empty using JavaScript?

Object is the most important data type, and we require its most of the time while developing the application with the JavaScript framework. Sometimes, we need to check whether an object is empty and perform the operation based on the object value.

For example, you are fetching the data from the database; if it isn’t found, you can get an empty object. When you perform some operation or execute some method on an empty object, it raises an error in the program. So, it’s better first to check whether the object is empty.

Use the Object.keys() Method

We can use the Object.keys() method to get the object’s keys in the single array. After that, we can check the array’s length using the array’s length property. If the length of the array of keys is 0, that means the object doesn’t contain any key, and the object is empty.

Syntax

Users can follow the syntax below to check whether the object is empty using the Object.keys() method.

let obj1Len = Object.keys(obj1).length;
if (obj1Len == 0) {
   
   // object is empty
} else {
   
   // object is not empty
}

In the above syntax, Object.keys() returns the array of all keys of obj1, and we have used the length property to get its length. Using above syntax, we can get the array of all keys using the Object.keys() method, and also we can check the length of the array using the length property.

Use the for-in loop

The for-in loop allows us to iterate through the object’s keys. We can iterate through every key of an object using the for-in loop. Here, we will use the for-in loop and check that if it makes a single iteration for the object, the object contains at least one property and is not empty.

Syntax

Users can follow the syntax below to check whether the object is empty using the for-in loop.

function isObjectEmpty(object) {
   for (ele in object) {
      
      // object is not empty
      return;
   }
   
   // if control comes here, the object is empty
} 

In the above syntax, if the single iteration of the for-loop occurs, that means we have ensured that object contains at least one property. So, we terminate the function using the return keyword after the first iteration of the for-in loop.

Use the JSON.stringify() Method

The JSON.stringify() method converts any value to a string which we pass as an argument of the method. The syntax of the empty object is like {}, and stringify() method always returns the “{}” for the empty object.

So, we can compare the return value of the stringify() method with the “{}” and ensure that the object is empty or not.

Syntax

Users can follow the syntax below to use the JSON.stringify() method to check if the object is empty.

if(JSON.stringify(education) == "{}") {
   
   // object is empty
} else {
   
   // object is not empty
}

In the above syntax, JSON.stringify() method returns the “{}” if the education object is empty.