How to Check if an Object Is Empty in JavaScript
Checking whether a JavaScript object has any keys.
There are times when you need to know if an object has anything in it, like when
an API returns {} instead of your data or a form has no errors. Arrays have a
length property for this, but objects don't, so you need a different approach.
Why the Obvious Checks Don't Work
Your first guess might be to check if the object is truthy or compare it to
{}:
const user = {}if (!user) {// never runs, an empty object is truthy}console.log(user === {}) // false
An empty object is still an object, so it's truthy. And comparing objects with
=== checks if they're the same object in memory, not if they have the same
contents. Two separate {} are never equal.
Using Object.keys()
The simplest way is to get the object's keys with Object.keys and check the length of that array:
const isEmpty = (obj) => Object.keys(obj).length === 0isEmpty({}) // trueisEmpty({ name: "Jim" }) // false
Making Sure It's an Object
Object.keys also works on other values, which can give you surprising results:
isEmpty(new Date()) // trueisEmpty([]) // true
If you only want plain objects to count, check the constructor too:
const isEmptyObject = (obj) =>Object.keys(obj).length === 0 && obj.constructor === ObjectisEmptyObject({}) // trueisEmptyObject(new Date()) // falseisEmptyObject([]) // false
Note: Object.keys throws an error on null and undefined, so check for
those first if your value might not exist.
const isEmptyObject = (obj) =>obj != null && Object.keys(obj).length === 0 && obj.constructor === Object
Using a for...in Loop
If you need to support older browsers or want to stop as soon as a key is found,
a for...in loop works too:
function isEmpty(obj) {for (const key in obj) {if (obj.hasOwnProperty(key)) {return false}}return true}
The loop returns false on the first key it finds. hasOwnProperty makes sure
the key belongs to the object itself and isn't inherited.
For most cases Object.keys(obj).length === 0 is all you need.
Have some feedback on this post? .