How to Check if an Object is Empty in JavaScript

JavaScript is an object-oriented programming language and so objects are everywhere.
When working with objects, you will want to know whether or not it is empty, usually for validation purposes.
In this post, we'll look at the best way to check if a JavaScript object is empty.
Checking if an Object is Empty
The best way to check if an object is empty is to take a look at how many keys it contains.
Remember, objects are basically a collection of key-value pairs, so if there are no keys, there are no values.
To check the number of keys in an object, we can use the Object.keys
method.
const object = {};
const keys = Object.keys(object);
Now that we have the keys in an array, we can do a simple length check on it to see if it is empty.
const object = {};
const keys = Object.keys(object);
if (keys.length === 0) {
// Object is empty
}
You can condense this into a single line:
const isEmpty = Object.keys(object).length === 0;
Just to illustrate the point, we can try this on an object that is clearly not empty and see what we get:
const object = {
key: "value"
};
const keys = Object.keys(object);
if (keys.length === 0) {
console.log("Object is empty");
} else {
console.log("Object is not empty");
}
Object is not empty
Conclusion
In this post, we took a look at the recommended way to confirm that an object in JavaScript is empty.
Simply do a length check on the number of keys from the Object.keys
method, and if it is 0, the object is empty.
Thanks for reading!
Leave us a message!