Checking whether an object is empty is a common and repetitive task for JavaScript and TypeScript developers. It is crucial in cases where the object holds the data from the database, user input, or API. One should always verify the existence of data before proceeding to further operations.

Note: The article describes the methods which apply to both JavaScript and TypeScript, as TypeScript is a superset of JavaScript. We will refer to JavaScript for simplicity.

To check for an empty object in JavaScript, you can verify the variable type is an object, retrieve the array of the object’s keys, get its length and ensure the length equals zero. The Object.keys() method comes in handy to retrieve the array of keys in the object.

The forthcoming sections in the article will describe the detailed process of checking whether the object is empty.

Check for an Empty Object in JavaScript Using the Object.keys() Method

As stated earlier in the article, the Object.keys() method returns an array of the keys of the object passed to it. Since you have the array, you can easily check whether it has contents using the length property. If the array’s length equals 0, you can be sure that the object is empty.

Additionally, verifying whether the variable to be checked is an object is good. For that, you can use the typeof keyword and check the variable’s type against the string 'object'. The complete example is shown below.

const data = {
   name:"Subodh",
   age:23
}

const message = typeof data == 'object' && Object.keys(data).length === 0 ? "object is empty": "object is not empty"
console.log(message)//"object is not empty"

Since the object data in the example contains values, the output will show that the object is not empty. The example uses the ternary operator for the check. If you are unfamiliar with the ternary operator, you might consider the following if-else alternative.

const data = {
   name:"Subodh",
   age:23
}

if (typeof data == 'object' && Object.keys(data).length === 0){
   console.log('object is empty')
} else {
   console.log('object is not empty') // this gets printed
}

Other Methods

You probably might have wondered that there must also be other methods to check whether the object is empty in JavaScript. You are correct! Now let’s explore these different methods of performing the check.

Check for an Empty Object in JavaScript Using the Object.values() Method

Apart from finding the array of keys in an object to check for an empty object, you can also perform the check by retrieving the array of values. Both methods produce a similar result as the length of the item in the array will be the same.

JavaScript provides the method Object.values() to extract only the values from an object and return it as an array. Although the content of the returned array is a little different from the arrays returned by Object.keys(), it will do the job. Let’s see an example of how Object.values() functions.

const data = {
   name:"Subodh",
   age:23
}

console.log(Object.values(data)) // [ 'Subodh', 23 ]

The output contains the array of the values of the data object. Since you have the array, you can verify its length using the length property.

const message = typeof data == 'object' && Object.values(data).length === 0 ? "object is empty": "object is not empty"
console.log(message)//"object is not empty"

Check for an Empty Object in JavaScript Using the Object.entries() Method

The Object.entries() is another JavaScript method that returns a similar kind of array as the methods above, which is useful while checking for an empty object. Unlike the other two methods discussed above, Object.entries() converts the entire object to an array. Each key/value pair of the object form an item in the array.

const data = {
   name:"Subodh",
   age:23
}

console.log(Object.entries(data)) // [ [ 'name', 'Subodh' ], [ 'age', 23 ] ]

Since the length of the arrays is the same in all the cases, the latter part, finding the length of the array to check for the empty object, is common in all methods.

const message = typeof data == 'object' && Object.entries(data).length === 0 ? "object is empty": "object is not empty"
console.log(message)//"object is not empty"

Check for an Empty Object in JavaScript Using the hasOwnProperty() Method

The other alternative to check for an empty object in JavaScript is to check whether a property is the object’s own property by iterating over the object. If such property exists, you can ensure that the object is not empty. You can achieve the solution by implementing a for...in statement and using the hasOwnProperty() method. This can be your method of choice if your browser does not support the methods like keys(), values(), and entries().

function isEmpty(infos) {
  for (info in infos) {
    if (infos.hasOwnProperty(info)) {
      return false
    }
  }
  return true
}

console.log(isEmpty({
  name: "Subodh",
  age: 23

})) // false
console.log(isEmpty({})) // true

In the code snippet above, the for..in statement lets you access each property of the infos object as info. Next, hasOwnProperty() checks whether info is infosobject’s own property. If the property does not exist, you can ensure that the object is empty.

As shown in the example, the isEmpty() function returns false (object is not empty) when a non-empty object is passed to it. And, when an empty object is passed to the function, it returns true (object is empty).

Check for an Empty Object in JavaScript Using the JSON.stringify() Method

Converting an object to a JSON string and checking whether the JSON string is empty is also another alternative to checking for an empty object in JavaScript. The JSON.stringify() method converts a JavaScript object into a JSON string.

console.log(JSON.stringify({
  name: "Subodh",
  age: 23
}))
// {"name":"Subodh","age":23}

console.log(JSON.stringify({})) 
//{}

If the converted JSON string equals an empty JSON string such that '{}', you can be certain that the object is empty.

function isEmpty(infos) {
  if (JSON.stringify(infos) === '{}'){
     return true
  }
  return false
}

console.log(isEmpty({
  name: "Subodh",
  age: 23

})) // false
console.log(isEmpty({})) // true

The example above converts the objects passed to the isEmpty() function into JSON string and determines whether the object is empty.

Conclusion

This article presented a number of solutions to determine if an object is empty in JavaScript and TypeScrtipt. In summary, you can use the static Object methods entries(), keys(), values() along with the length property, the hasOwnProperty in a loop and the JSON.stringify() method to check for an empty object.

Did you gain an understanding from the article?

Let us know your thoughts by replying on twitter of Become A Better Programmer.

Author