DEV Community

loading...
Cover image for πŸ€” Check if an object is empty in JS

πŸ€” Check if an object is empty in JS

Benjamin Mock
I'm Ben, a Frontend Developer from Germany working at ebay
Originally published at codesnacks.net ・2 min read

Checking if an object is empty, is a quite common task. Let's figure out how to accomplish it.

Here we create an empty object using the object literal syntax.

const someObject = {}

You might be tempted to compare this object, to an empty object like this:

const someObject = {}
console.log(someObject === {}) // false

That's incorrect. Even if you compare two objects via the object literal, they're not equal:

console.log({} === {}) // false

This is because you're comparing reference and not values. The reference to these objects isn't the same, even though the value is the same.

So how can we actually check if an object is empty? You could do so, by checking if it has any properties. We could use the Object.entries method, which returns an array of all the properties of the object.

const someObject = {}
console.log(Object.entries(someObject).length === 0) // true

If you want to create a small function, it would make sense to first check if we're actually dealing with an object, to not throw any errors, if a wrong data type is checked:

const isEmpty = obj => obj.constructor === Object && !Object.entries(obj).length

// let's see if it works:
const o = {}
console.log(isEmpty(o)) // true

o.name = "foo"
console.log(isEmpty(o)) // false

Also, lodash offers an isEmpty utility function to check if an object is empty:

const someObject = {}
console.log(_.isEmpty(someObject)) // true

Want to get better at Web Development?
πŸš€πŸš€πŸš€subscribe to my Tutorial Tuesday βœ‰οΈnewsletter

Discussion (3)

Collapse
dhruvpatel profile image
Dhruv

I usually tend to check obj && Object.keys(obj) > 0 for non-empty object check

Collapse
verycosy profile image
Jinho Jang

Cool !

Collapse
dhihendrix profile image
Dhiego Hendrix Atencio

lodash - isEmpty(obj)