This page looks best with JavaScript enabled

Check if objects are empty in Javascript

 ·   ·  ☕ 2 min read

Check if a given object is empty without considering any custom props defined by prototype.

Consider this sample object -

1
const earth = {};

Use Object.entries() or equivalent

Object.entries gives us a short way to access entries in an array form. We could just check whether entries are empty to decide whether the parent object is empty.

1
2
3
4
5
6
const earth = {};

const isEmpty = !Object.entries(earth).length;
console.log(isEmpty);

// true

The above logic is unaffected even if the object has defined properties.

1
2
3
4
5
6
7
8
const earth = {};

Object.defineProperty(earth, "life", Boolean);

const isEmpty = !Object.entries(earth).length;
console.log(isEmpty);

// true

You could also use comparable functions that retrieve keys or values from an object.

1
2
3
4
5
6
7
const earth = {};

console.log(Object.values(earth).length);
// 0

console.log(Object.keys(earth).length);
// 0

Use a custom function with hasOwnProperty

To check if earth is empty, you can just do -

1
2
3
4
5
6
7
8
9
console.log(isEmpty(earth)); // true

function isEmpty(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) return false;
    // alternative: define prop as not enumerable and don't use hasOwnProperty
  }
  return true;
}

If the object is not empty..

1
2
const earth = { name: "earth", position: 3 };
console.log(isEmpty(earth)); // false

What not to do?

Note that you cannot check the object directly to check a truthy condition.

1
2
3
4
5
6
const earth = new Object();
if (earth) console.log("earth is not empty");
// earth is not empty

const mars = { population: 1 };
console.log("Mars is empty: ", !!mars); // true

Recommendation

Use Object.entries() to check empty conditions unless you really are in love with loops.

Already have an object? Check how you can empty an object in Javascript :)

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things