Sometimes you just need to know — is this object empty or not? Whether you’re validating input, cleaning up data, or writing logic to skip empty configs, checking if an object has no keys is a common task in JavaScript.
Here’s the simplest and most reliable way to do it:
const obj = {};
if (Object.keys(obj).length === 0) {
console.log('Object is empty!');
}
Let’s break it down:
Object.keys(obj)
returns an array of all enumerable property names.- If the array’s length is
0
, the object is empty — plain and simple.
Sometimes you get unexpected input — especially when dealing with APIs, user input, or dynamic data.
Let’s say you do this:
const maybeEmpty = null;
if (Object.keys(maybeEmpty).length === 0) {
// ...
}
You get this error: TypeError: Cannot convert undefined or null to object
.
Or consider this:
const maybeEmpty = [];
Object.keys(maybeEmpty).length === 0; // true
That’s technically true, but an empty array isn’t an empty object. If you’re checking for config values or input data, treating an array as an empty object might introduce bugs.
So, the solution is to wrap your check in a function that:
- Ensures the value is not
null
- Confirms it’s a plain object
- Excludes arrays
- Then checks for keys
function isEmptyObject(obj) {
return !!obj &&
typeof obj === 'object' &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0;
}
isEmptyObject([]) // false
isEmptyObject(null) // false
isEmptyObject({}) // true
Now it’s safe, clean, and reusable.
Want more dev insights like this? Subscribe to get practical tips, tutorials, and tech deep dives delivered to your inbox. No spam, unsubscribe anytime.