/

How to Test for an Empty Object in JavaScript

How to Test for an Empty Object in JavaScript

Today, I encountered a situation where I needed to determine if an object was empty in JavaScript. However, straightforward comparisons using the equality operator (===) won’t work because JavaScript objects are compared by reference, not by contents.

In order to effectively check if an object is empty, we can utilize the built-in method Object.keys() and an additional check on the object’s constructor.

Here’s an example solution:

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

if (Object.keys(obj).length === 0 && obj.constructor === Object) {
// Object is empty
// Add your desired logic here
}

By using Object.keys(obj) we extract all the keys of the obj object into an array. This allows us to determine its length using .length. If the length is 0, it means the object is empty.

But wait, there’s one more important step. To avoid false positives, we need to check if the object’s constructor is the Object constructor. This additional check ensures that we only consider literal objects and not instance objects of custom classes or other object types.

Feel free to implement your desired logic inside the if statement to handle the case when the object is empty.

Tags: JavaScript, object, empty-check