Skip to content

How to Check if Object Is Empty in Javascript

There are many ways to check if an Object is empty or not. But in this post we will document only which is recommended and has fast execution compared to others.

for loop

Iteration is best way to check if Object is empty or not and it will work on all the browsers.

const obj = {};

for(let key in obj) {
    if(obj.hasOwnProperty(key)) {
        return false;
    };
};
return true;

Using Object.keys

obj // check if obj is not null or undefined
&& Object.keys(obj).length === 0 // check if object has no keys
&& obj.constructor === Object // check if constructor of object is of Object type

In Javascript, new keyword creates a new Object. For Example. new String() is also an Object but its constructor type is string.

const str = new String(); // typeof str = Object
str.constructor(); // string

Snippet

const obj = {};
// check if object is empty
if(obj && Object.keys(obj).length === 0 && obj.constructor === Object) {
    return true;
};
return false;

References

Checkout these resources for more options