In JavaScript development, determining if an object is empty isn’t just a common task — it’s a necessary skill that helps write robust, safe, and efficient code. Whether you’re verifying the response from an API, checking form values, or handling optional configurations, knowing whether an object contains properties can be crucial.
TL;DR
To check if a JavaScript object is empty, use Object.keys(obj).length === 0 as a reliable method. For better clarity, also validate that the object is not null or undefined. Avoid using JSON methods for this purpose, and remember that objects from other sources like DOM nodes or custom classes may need additional checks. By using the appropriate method, you can make your code more robust and error-free.
Why Check if an Object is Empty?
JavaScript is a dynamic language, and objects can be manipulated easily — properties can be added or removed at any moment. But the simplicity of objects comes with complexity: how do you reliably tell if an object has no properties at all? Checking if an object is empty is useful when:
- Validating API responses
- Preventing null or undefined errors
- Ensuring optional configuration parameters are set
- Controlling UI elements based on received data
Thus, determining object emptiness is a fundamental tool in every JavaScript developer’s toolbox.
Understanding “Empty”
An “empty” object in JavaScript is one that has no own enumerable properties. For example:
const obj = {};
Contrast that with:
const obj2 = { name: "JavaScript" };
While obj is empty, obj2 is not, because it has a name property. But beware — inheritance, non-enumerable properties, or class-based structures can complicate this, so let’s explore the most common ways to check if an object is truly empty.
1. The Recommended Method: Object.keys()
The simplest and most common way to validate an object’s emptiness is:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
Why this works: Object.keys() returns an array of the object’s own enumerable property names. If that array is empty, then the object has no own properties and is therefore empty.
This method does not account for inherited properties, which is typically what you want when checking standard JSON-like objects.
2. Object.entries() and Object.values()
These two cousins of Object.keys() serve similar purposes:
Object.entries(obj).length === 0;
Object.values(obj).length === 0;
They’re equally valid for checking if an object is empty. The difference is:
Object.entries()returns key-value pairs as arraysObject.values()returns only the values
But all return empty arrays if the object has no properties.
3. Using for…in Loop and hasOwnProperty()
This method avoids creating arrays and can be slightly more performant in performance-critical scenarios:
function isEmpty(obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
Pros: Efficiency in memory and garbage collection.
Cons: Slightly longer syntax and potentially less readable.
4. JSON.stringify (Not Recommended)
You might see code like this:
JSON.stringify(obj) === "{}"
While it can work in very simple cases, it has risks:
- It can omit non-enumerable properties
- It converts objects to a string, adding unnecessary overhead
- It can hide errors in complex objects or classes
TLDR: It’s a shortcut, and like most shortcuts, it’s risky and should be avoided.
What About null or undefined?
Objects in JavaScript can also be null or undefined, which causes Object.keys() and other methods to throw an error.
Safe practice:
function isEmpty(obj) {
return (
obj &&
typeof obj === 'object' &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0
);
}
This method ensures you’re checking only objects and not arrays or falsy values like null.
Exclude Arrays and Functions
Arrays and functions are technically objects too, but they should be excluded from this type of check in many cases.
function isTrulyEmpty(obj) {
return (
obj &&
typeof obj === 'object' &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0
);
}
This version adds a filter to exclude arrays and maintain correctness.
When Inherited Properties Are Involved
Objects created with prototypes — such as instances of a class — can inherit properties that aren’t directly present on the object. If you’re only interested in own properties, use Object.hasOwnProperty() or stick with Object.keys().
class Config {
constructor() {
this.name = "Default";
}
}
const myConfig = new Config();
console.log(Object.keys(myConfig).length); // 1
But if an object has inherited properties but none on itself, it should still be considered empty for many practical purposes.
Comparing Performance (Optional Depth)
If you’re a performance-conscious developer, you might wonder how these methods compare speed-wise. In typical web app usage, the difference is negligible, but in loops or large-scale operations, avoiding array creation (i.e., sticking to for...in) might offer micro-optimizations.
Object.keys(): clean and readable, slightly more memory usefor...in: performant in large data sets, but less intuitive
In most cases, readability should outweigh micro-optimizations.
Using a Utility Library
If you’re using libraries like Lodash or Underscore.js, you can use:
_.isEmpty(obj)
This handles null checks, array exclusion, and more — safe and seasoned. But be careful not to bloat your project with unnecessary dependencies just for this one feature.
Conclusion
Checking if a JavaScript object is empty is both simple and nuanced. Though Object.keys(obj).length === 0 is the most widely accepted method, be sure to enhance your checks depending on your needs — especially when dealing with objects that may inherit properties or originate from external sources.
Here’s a quick recap of the most reliable method:
function isEmpty(obj) {
return (
obj &&
typeof obj === 'object' &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0
);
}
If you follow this approach, you’ll avoid common bugs and write more resilient code, ready for today’s ever-changing web applications. Happy coding!
