How to Check if an Object is Empty or not in JavaScript?

An object in JavaScript is an unordered collection of key-value pairs. And when the object has no key-value pairs, we call it an empty object.

To check if the object is empty or not, you can use the Object.keys() method. The Object.keys() method takes in an object as a parameter and returns an array that contains all of the object’s keys.

This means if the length of the keys array returned by the Object.keys() method is zero, the object is empty, otherwise, it’s not.

// Empty object
const obj = {};

// Check if keys array is empty
if(Object.keys(obj).length===0){
    console.log("Object is empty");
}
else{
    console.log("Object isn't empty");
}

If the object is non-empty, the Object.keys() method returns an array containing all keys of the object.

See the following example:

// Non-empty object
const obj = {
    name: 'John',
    age: 24
}

console.log(Object.keys(obj));
// Output: ["name", "age"]

2. Use JSON.stringify()

The JSON.stringify() method converts an object into a string. We can use this method to check if the object is empty or not by converting it into a string and then comparing it with the '{}' string.

// Empty object
const obj = {};

// Stringify and compare
let isEmpty = (JSON.stringify(obj)==='{}');

console.log(isEmpty);
// Output: true

For non-empty objects, this method will return a boolean false.


3. Use for…in Loop

You can also loop through the object using the for...in loop and then check if the loop runs at least one time. If yes, then the object isn’t empty, otherwise, it is empty.

Here is the code:

// Empty object
const obj = {};

// Set a boolean flag
let isEmpty = true;

// Loop through the object
for(let key in obj){
    isEmpty = false;
    break;
}

console.log(isEmpty);
// Output: true

For the non-empty objects, the isEmpty flag will be boolean false.


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.

    View all posts