In this article, we will learn to check if the object is empty in Javascript. There are multiple ways to find it out. We are going explore every way in this article.
Different Ways to check if the Object is Empty in Javascript or Typescript
1. Using Object.keys() Method
Sample Code
const obj = {}; const isEmpty = Object.keys(obj).length === 0; // true
In the above method, we are checking for the enumerable property names in the object using the Object.keys() method and getting its length. The object is not empty if its length is more than 1.
2. Using Object.values() Method
Sample Code
const isEmptyValues = Object.values(obj).length === 0; // true
Object.values() method returns an array of the object’s own enumerable property values.
3. Using Object.entries() Method
Sample Code
const isEmptyEntries = Object.entries(obj).length === 0; // true
Object.entries() method returns an array of key-value pairs from the object.
4. Using For…in Loop with hasOwnProperty() Method
Sample Code
function isEmpty(obj) { for (const prop in obj) { if (obj.hasOwnProperty(prop)) { return false; } } return true; }
The hasOwnProperty() method ensures checking only owned properties and not the inherited ones.
5. Using JSON.stringify() Method
Sample Code
const isEmpty = JSON.stringify(obj) === '{}'; // true
In the above method, we are converting the Object to string comparing it with the stringified empty braces ‘{}’ which returns true if the object matches with it.
6. Using Libraries
Few libraries have dedicated methods to find out whether the object is empty.
a. Using Jquery
Sample Code
// jQuery const isEmpty = $.isEmptyObject(obj);
In Jquery, we have isEmptyObject() method which tells us whether the object is empty or not.
b. Using Lodash
Sample Code
// Lodash const isEmpty = _.isEmpty(obj);
In Lodash, we have isEmpty() method to determine whether the object is empty.
Among all the methods mentioned above, Object.keys() is generally efficient and widely supported. And if we don’t want to write a separate method for it and if we can use libraries, using Lodash library can be reliable choice for these kind of tasks.