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 – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of… Read more: JavaScript – Sum of Digits of a Number
- 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