How to check if an object is empty in JavaScript

By

Learn how to check if an object is empty in JavaScript using Object.entries().length and a constructor check, plus the Lodash isEmpty() shortcut.

~~~

To check if an object is empty in JavaScript, check that Object.entries(objectToCheck).length is 0, and that its constructor is Object. Let’s see why we need both.

Say you want to check if a value you have is equal to the empty object, which can be created using the object literal syntax:

const emptyObject = {}

How can you do so?

You can’t compare it with {} directly, because objects are compared by reference, and two different objects are never equal:

const settings = {}
settings === {} //false

Counting the properties

Use the Object.entries() function.

It returns an array containing the object’s enumerable properties.

It’s used like this:

Object.entries(objectToCheck)

If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

Object.entries(objectToCheck).length === 0

Object.keys() works the same way, if you prefer it. Both only look at the object’s own properties, not the ones inherited through the prototype chain, which is what we want here.

Why check the constructor too?

Lots of values that are not plain objects also have zero enumerable properties. A Date is one example:

Object.entries(new Date()).length === 0 //true

A date is clearly not an empty object, so the length check alone can lie to you.

That’s why you should also make sure the value is actually a plain object, by checking its constructor is the Object object:

objectToCheck.constructor === Object

Putting the two together:

const isEmptyObject = (value) => {
  return value.constructor === Object && Object.entries(value).length === 0
}

Be careful with null and undefined

Both checks throw a TypeError if the value is null or undefined, because you can’t read constructor on them, and Object.entries(null) fails too.

If the value might be missing, guard against that first:

const isEmptyObject = (value) => {
  return (
    value !== null &&
    value !== undefined &&
    value.constructor === Object &&
    Object.entries(value).length === 0
  )
}

Now isEmptyObject(null) returns false instead of crashing.

Lodash, a popular library, makes it simpler by providing the isEmpty() function:

_.isEmpty(objectToCheck)

Note that Lodash considers null, undefined, empty arrays and empty strings all empty, so it answers a broader question than “is this an empty object”. For most cases that’s exactly what you want.

~~~

Related posts about js: