DEV Community

Cover image for πŸ€” Check if an object is empty in JS
Benjamin Mock
Benjamin Mock

Posted on β€’ Originally published at codesnacks.net

21 7

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

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more