DEV Community

Sujit Kar
Sujit Kar

Posted on • Edited on

How to check Javascript object is empty or not?

This is tricky but not difficult.

const obj = {};
if( ( Object.keys(obj) ).length === 0){
 console.log("Object is empty");
}
else{
 console.log("Object is not empty");
}
Enter fullscreen mode Exit fullscreen mode

How this works?

Because, with the help of keys property of the Object class it creates an array of keys of obj. And the array has length property to find its length. If length is 0 then the obj is empty otherwise not.

If any doubts kindly ask me.

Thanks!!!
@sujitkar1195

Top comments (0)