DEV Community

Cover image for How to Check if Object is Empty in JavaScript

How to Check if Object is Empty in JavaScript

Samantha Ming on July 15, 2020

Here's a Code Recipe to check if an object is empty or not. For newer browsers, you can use plain vanilla JS and use the new "Object.keys" 🍦 But ...
Collapse
 
prahladyeri profile image
Prahlad Yeri

A typical programming practice is to set your object variable as undefined at first, so that comparison becomes much simpler for that later in code. All you have to do is:

var foo = undefined;
....
if (foo===undefined) doSomething();
....

The same holds true when you return a function value, return either a boolean or undefined as a falsy value to avoid trouble latter.

Collapse
 
pentacular profile image
pentacular

The real question is -- why would you ever want to check that an object is empty?

Collapse
 
functional_js profile image
Functional Javascript

I've only used my isEmptyObj in sanitization code.
Cleaning out empty values from incoming data.

Collapse
 
pentacular profile image
pentacular

Hmm, I still can't figure out why you'd ever want to do that.

Surely you want to check the object for having some set of required and forbidden properties.

Checking for an empty object seems completely useless, because if you wanted an empty object you could just make one yourself.

And if you didn't want an empty object, that means that you want some object with some properties, in which case you can check for the properties that you want.

So, I still can't figure out why you'd ever want to check if an object is empty.

Collapse
 
functional_js profile image
Functional Javascript • Edited

Excellent work Samantha.

I made the adjustment to my isObj func

Alt Text

Source Code at:

gist.github.com/funfunction/b4b418...

Update:

I posted a more comprehensive (fuzz) test and performance analysis here....
dev.to/functional_js/isobj-test-if...

Collapse
 
samanthaming profile image
Samantha Ming

wooo, thanks for sharing let me link it up in my code notes 👍

Collapse
 
miteshkamat27 profile image
Mitesh Kamat

Great we can add this as helper function in our codebase.

Collapse
 
devansvd profile image
Devan • Edited

I use this often
image

Collapse
 
samanthaming profile image
Samantha Ming

Nice, I like this! You wouldn't have this code somewhere, would you? -- I'd love to include it in my code notes. But no biggie if you don't, I can type it out too 😄

Collapse
 
mohsenalyafei profile image
Mohsen Alyafei

Sometimes it is necessary to check if an object is empty.
Thanks

Collapse
 
lazydeveloper profile image
Shiva

Good Explanation !!

Collapse
 
samanthaming profile image
Samantha Ming

awesome! glad you found it helpful! thanks for reading my article 👏

Collapse
 
mithunkumarc profile image
ಮಿಥುನ್ • Edited

thanks, its valuable info. As a beginner in java script, i think
let o = new object();
still an empty object. i got confused in the beginning.