How to Check if Object Is Empty in Javascript

Sunday, April 18, 2021 • One minute to read

Javascriptto-the-point2021javascriptto-the-point2021

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.

1const obj = {};
2
3for(let key in obj) {
4    if(obj.hasOwnProperty(key)) {
5        return false;
6    };
7};
8return true;

Using Object.keys

1obj // check if obj is not null or undefined
2&& Object.keys(obj).length === 0 // check if object has no keys
3&& 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.

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

Snippet

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

References

Checkout these resources for more options


Javascriptto-the-point2021javascriptto-the-point2021

PreviousHow to Get the Length of an Object in Javascript

NextHow to Add and Remove a Property of an Object in Javascript