JavaScript – Check if an object is empty

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