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

How to Check if Object is Empty in JavaScript

samanthaming profile image Samantha Ming Originally published at samanthaming.com ใƒป5 min read

Code snippet of How to Check if Object is Empty in JavaScript for newer browser and older browser

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 for older browser support, you can install the Lodash library and use their "isEmpty" method ๐Ÿค–

const empty = {};

/* -------------------------
  Plain JS for Newer Browser
----------------------------*/
Object.keys(empty).length === 0 && empty.constructor === Object
// true

/* -------------------------
  Lodash for Older Browser
----------------------------*/
_.isEmpty(empty)
// true

What is Vanilla JavaScript

Vanilla JavaScript is not a new framework or library. It's just regular, plain JavaScript without the use of a library like Lodash or jQuery.

A. Empty Object Check in Newer Browsers

We can use the built-in Object.keys method to check for an empty object.

const empty = {};

Object.keys(empty).length === 0 && empty.constructor === Object;

Why do we need an additional constructor check?

You may be wondering why do we need the constructor check. Well, it's to cover for the wrapper instances. In JavaScript, we have 9 built-in constructors.

new Object();

new String();
new Number();
new Boolean();
new Array();
new RegExp();
new Function();
new Date();

So we can create an empty object with new Object(). Side note: you should NEVER create an object using the constructor. It's considered bad practice, see Airbnb Style Guide and ESLint.

const obj = new Object();

Object.keys(obj).length === 0; // true

So just using the Object.keys, it does return true when the object is empty โœ…. But what happens when we create a new object instance using these other constructors.

function badEmptyCheck(value) {
  return Object.keys(value).length === 0;
}

badEmptyCheck(new String());    // true ๐Ÿ˜ฑ
badEmptyCheck(new Number());    // true ๐Ÿ˜ฑ
badEmptyCheck(new Boolean());   // true ๐Ÿ˜ฑ
badEmptyCheck(new Array());     // true ๐Ÿ˜ฑ
badEmptyCheck(new RegExp());    // true ๐Ÿ˜ฑ
badEmptyCheck(new Function());  // true ๐Ÿ˜ฑ
badEmptyCheck(new Date());      // true ๐Ÿ˜ฑ

Ah ya ya, we have a false positive ๐Ÿ˜ฑ

Solving false positive with constructor check

Let's correct this by adding a constructor check.

function goodEmptyCheck(value) {
  Object.keys(value).length === 0
    && value.constructor === Object; // ๐Ÿ‘ˆ constructor check
}

goodEmptyCheck(new String());   // false โœ…
goodEmptyCheck(new Number());   // false โœ…
goodEmptyCheck(new Boolean());  // false โœ…
goodEmptyCheck(new Array());    // false โœ…
goodEmptyCheck(new RegExp());   // false โœ…
goodEmptyCheck(new Function()); // false โœ…
goodEmptyCheck(new Date());     // false โœ…

Beautiful! We have covered our edge case ๐Ÿ‘

Testing empty check on other values

Alright, let's test our method on some values and see what we get ๐Ÿงช

function isEmptyObject(value) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}

Looks good so far, it returns false for non-objects.

isEmptyObject(100)  // false
isEmptyObject(true) // false
isEmptyObject([])   // false

๐ŸšจBut watch out! These values will throw an error.

// TypeError: Cannot covert undefined or null ot object
goodEmptyCheck(undefined)
goodEmptyCheck(null)

Improve empty check for null and undefined

If you don't want it to throw a TypeError, you can add an extra check:

let value;

value // ๐Ÿ‘ˆ null and undefined check
 && Object.keys(value).length === 0 && value.constructor === Object;

value = null;       // null
value = undefined;  // undefined

Perfect, no error is thrown ๐Ÿ˜

B. Empty Object Check in Older Browsers

What if you need to support older browsers? Heck, who am I kidding! We all know when I say older browsers, I'm referring to Internet Explorer ๐Ÿ˜‚ Well, we have 2 options. We can stick with vanilla or utilize a library.

Checking empty object with JavaScript

The plain vanilla way is not as concise. But it does do the job ๐Ÿ‘

function isObjectEmpty(value) {
  return Object.prototype.toString.call(value) === "[object Object]" && JSON.stringify(value) === "{}"
}

It returns true for objects.

isObjectEmpty({});           // true โœ…
isObjectEmpty(new Object()); // true โœ…

Excellent, it doesn't get trick by our constructor objects ๐Ÿ˜‰

isObjectEmpty(new String());   // false โœ…
isObjectEmpty(new Number());   // false โœ…
isObjectEmpty(new Boolean());  // false โœ…
isObjectEmpty(new Array());    // false โœ…
isObjectEmpty(new RegExp());   // false โœ…
isObjectEmpty(new Function()); // false โœ…
isObjectEmpty(new Date());     // false โœ…

And we're covered for null and undefined. It will return false and not throw a TypeError.

isObjectEmpty(null);      // false
isObjectEmpty(undefined); // false

Checking empty object with external libraries

There are tons of external libraries you can use to check for empty objects. And most of them have great support for older browsers ๐Ÿ‘

Lodash

_.isEmpty({});
// true

Underscore

_.isEmpty({});
// true

jQuery

jQuery.isEmptyObject({});
// true

Vanilla vs Libraries

The answer is it depends! I'm a huge fan of going vanilla whenever possible as I don't like the overhead of an external library. Plus for smaller apps, I'm too lazy to set up the external library ๐Ÿ˜‚. But if your app already has an external library installed, then go ahead and use it. You will know your app better than anyone else. So choose what works best for your situation ๐Ÿ‘

Conscious Decision Making

  • @lexLohr: Like most things in development, it's a compromise. A good developer is aware of the available options. A great developer is also aware of their implications.

I love this mindset so much! Often, we have to make some compromises. And there's nothing wrong with that. Especially, when you work within a team, sometimes disagreement arises. But in the end, we have to make a decision. This doesn't mean we blind ourselves from other options. Quite the opposite, we do our best to seek other possible solutions and understand each implication. That's how we can make an informed decision. Maybe compromise is not the right word, I think of it as "conscious decision making" ๐Ÿ˜†

Yup, I too can coin terms, just like Gwyneth Paltrow's conscious uncoupling. Maybe I should start a tech version of Goop...but minus the jade roller and the other "interesting" products ๐Ÿ˜‚

Community Input

for (var key in object) {
  if (object.hasOwnProperty(key)) {
    return false
  }
}
return true
Object.prototype.toString.call(a) == "[object Object]" && JSON.stringify(a) == "{}"
  • @kevinsar: Lodash tends to throw security exceptions in analysis tools like sonarqube and whitesource, I tend to just create my own util function and use vanilla instead.

  • @functional_js: isNotObj Gist

Resources


Thanks for reading โค
To find more code tidbits, please visit samanthaming.com

๐ŸŽจInstagram ๐ŸŒŸTwitter ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ปSamanthaMing.com

Posted on by:

samanthaming profile

Samantha Ming

@samanthaming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits ๐Ÿ”ฅDiscover them all on samanthaming.com ๐Ÿ’›

Discussion

markdown guide
 

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.

 

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...

 

wooo, thanks for sharing let me link it up in my code notes ๐Ÿ‘

 

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

 

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

 

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.

 
 

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 ๐Ÿ˜„

 

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

 

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

 
 

awesome! glad you found it helpful! thanks for reading my article ๐Ÿ‘

 

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.