How To Check If An Object Is Empty In JavaScript

Introduction 

 
By default, JavaScript provides a property called length which could let you know if there are values inside the array, but when it comes to objects JavaScript doesn't provide any feature to determine if an object is empty. However, we could get around this issue easily by adding a tiny amount of code to your application.
 
In this blog post, we'll be looking at three different ways we can check if the object is empty.
 

Using the Object.keys method

 
The keys method returns an array that contains an array of property names of the object under consideration. We could check the length of this array to determine if an object is empty. If the object has no properties in it, i.e. it's empty, the array length will be zero. 
  1. const user = {};  
  2. Object.keys(user).length === 0; // Output: true  

Using for .. in loop

 
The for .. in statement is used to iterate over the enumerable properties of the object under consideration. 
  1. const user = {};  
  2.   
  3. function isEmpty(obj) {  
  4.     for (let key in obj) {  
  5.         if (obj.hasOwnProperty(key)) {  
  6.             return false;  
  7.         }  
  8.     }  
  9.   
  10.     return true;  
  11. }  
  12.   
  13. isEmpty(user); // Output: true  
The hasOwnProperty method on the object is used to determine if the property under consideration exists directly within the object or is being inherited from the prototype chain.
 

Using JSON.stringify method

 
The Stringify method converts the input into a string and returns that string. If we try to stringify an empty object, it'll simply return opening and closing curly brace as a string.
  1. const user = {};  
  2. JSON.stringify(user) === '{}' // Output: true  
Next Recommended Reading Initializing Empty Arrays in JavaScript