Skip to content

How to Check if Object is Empty – JavaScript

Use the following function to check if an object is empty:

function isObjectEmpty(obj) {
    return Object.keys(obj).length === 0 && // Checks the length of the object is 0
        Object.getPrototypeOf(obj) === Object.prototype; // Checks that it is actually an object

The first statement is self-explanatory – for an object to be empty, it must not have any keys. The second statement is there because JavaScript has an odd behaviour in handling types.

console.log(Object.keys(new Date()).length) // 0
console.log(Object.keys("key").length) // 3
console.log(Object.keys("").length) // 0

From the above, you can see that when a string is passed through, it counts the length of the string. Also when a Date is passed through, it also returns a length of 0. The second conditional checks that the type is actually an object to ensure these values do not inadvertently give a false positive.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.