How to Check if an Object is Empty in JavaScript?

To check if an object is empty or not, you can use the built-in Object.keys() method. The Object.keys() method returns an array of all the keys that are present in the object.

So, if the length of the keys array is 0, it means the object is empty otherwise it is not.

See the implementation below:

const obj = {}; // Empty object

const keys = Object.keys(obj); // []

if(keys.length==0){
    console.log('Object is empty');
}else{
    console.log('Object is not empty');
}

If the object isn’t empty, the Object.keys() method returns an array consisting of all the keys:

 const obj = {
   name: 'John',
   age: 25
}; 

const keys = Object.keys(obj); // Get the keys array

console.log(keys) // ["name", "age"]

An alternative approach could be to stringify the object and check if the result is equal to '{}' string. If it is so, then the object is empty otherwise it’s not.

See the implementation below:

const obj = {};  // Empty object

if(JSON.stringify(obj)==='{}'){
    console.log('Object is empty');
}else{
    console.log('Object is not empty');
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.