There are many ways to check if an object is empty. In this post we will explore two methods. Let’s dive in!
Using for loop
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}
console.log(isEmpty({})); // Output: true
console.log(isEmpty({ a: 1 })); // Output: false
Using Object.keys()
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmpty({})); // Output: true
console.log(isEmpty({ a: 1 })); // Output: false
Similar Reads
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of… Read more: JavaScript – Find the Intersection of Two Arrays