How to Check if an Object is Empty in JavaScript: 4 Different Ways
In JavaScript, checking if an object is empty (i.e., it has no properties) can be done in several ways. Object.keys() and Object.entries() are often used for this purpose. Here's a quick guide to four different methods to check if an object is empty in JavaScript.
1. Using Object.keys()
The Object.keys() method returns an array of the object's own enumerable property names. If this array is empty, then the object has no properties.
const obj = {};
if (Object.keys(obj).length === 0) {
console.log('The object is empty.');
} else {
console.log('The object is not empty.');
}
2. Using Object.entries()
The Object.entries() method returns an array of the object's own enumerable [key, value]
pairs. If this array is empty, then the object has no properties.
const obj = {};
if (Object.entries(obj).length === 0) {
console.log('The object is empty.');
} else {
console.log('The object is not empty.');
}
3. Using for...in Loop
You can use a for...in loop to check if there are any enumerable properties in the object. If the loop does not execute, the object is empty.
const obj = {};
let isEmpty = true;
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
isEmpty = false;
break;
}
}
if (isEmpty) {
console.log('The object is empty.');
} else {
console.log('The object is not empty.');
}
4. Using JSON.stringify()
Another method is to convert the object to a JSON string and check if it is equal to an empty object string {}
.
const obj = {};
if (JSON.stringify(obj) === '{}') {
console.log('The object is empty.');
} else {
console.log('The object is not empty.');
}
Conclusion
Each of these methods effectively determines if an object is empty. The choice of method can depend on the specific use case and preference. Object.keys()
and Object.entries()
are often preferred for their simplicity and readability. Happy Coding!!!
Follow and Support me on Medium and Patreon. Clap and Comment on Medium Posts if you find this helpful for you. Thanks for reading it!!!