To test if a JavaScript object is empty (has no own enumerable properties), use one of these methods:
1. Using Object.keys() (Modern & Recommended)
Check if the object’s keys array has a length of 0:
const isEmpty = (obj) => {
return Object.keys(obj).length === 0 && obj.constructor === Object;
};
// Example usage:
const user = {};
console.log(isEmpty(user)); // true
Key Notes:
Object.keys(obj).length === 0: Checks if the object has no own enumerable properties.obj.constructor === Object: Ensuresobjis a plain object (not an array ornull).
2. Using JSON.stringify()
Convert the object to a JSON string and check if it equals "{}":
const isEmpty = (obj) => {
return JSON.stringify(obj) === '{}';
};
// Example:
console.log(isEmpty({})); // true
console.log(isEmpty({ id: 1 })); // false
Limitations:
- Fails for objects with non-enumerable properties or custom
toJSON()methods. - Inefficient for large objects.
3. Using for...in Loop
Iterate over the object’s properties:
function isEmpty(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
// Example:
console.log(isEmpty({})); // true
console.log(isEmpty({ name: 'Alice' })); // false
Notes:
hasOwnProperty()ensures inherited properties (e.g., from prototypes) are ignored.
Edge Cases
- Non-Objects: Return
falsefor non-objects (e.g.,null,undefined, numbers):
isEmpty(null); // false
isEmpty(42); // false
- Arrays: Returns
falsefor empty arrays (useArray.isArray()first if needed):
isEmpty([]); // false (arrays are not plain objects)
- Objects with Prototype Properties:
const obj = Object.create({ inheritedProp: 'value' });
console.log(isEmpty(obj)); // true (ignores inherited properties)
Robust Solution (Combined Checks)
const isEmpty = (obj) => {
return (
obj && // Not null/undefined
typeof obj === 'object' && // Is an object
Object.prototype.toString.call(obj) === '[object Object]' && // Not an array
Object.keys(obj).length === 0
);
};
Summary
| Method | Pros | Cons |
|---|---|---|
Object.keys() | Fast, modern, handles most cases | Fails for non-plain objects (e.g., arrays) |
JSON.stringify() | Simple syntax | Fails for non-enumerable properties |
for...in | Works in older browsers | Verbose, slower |
Use Object.keys() for most use cases, and combine with type checks for robustness.