DEV Community

Chandra Prakash Pal
Chandra Prakash Pal

Posted on

Javascript how to check object is empty or not

In JavaScript everything start with object. Object has vital role while working with JavaScript.

We define object with two curly braces like

const user={};
later can add key value pairs in it like
user.name="User"
user.email="user@gmail.com"

But mostly we have to check that object is empty or not. So let's check it

const user={};

console.log(Object.keys(user).length) // will log 0

user.name="User"
user.email="user@gmail.com"
console.log(Object.keys(user).length) // will log 2

Top comments (2)

Collapse
 
sammi_mak_d80a57468774173 profile image
SammiMak

console.log(Object.values(user).length) // will log 2

Collapse
 
asmyshlyaev177 profile image
Alex

It's kinda anti-pattern to create an empty object and add properties to it later. Cleaner way is to use TS so object shape always known.