How to Check if Object is Empty in JavaScript
To check if an object is empty in JavaScript, use
Object.keys(obj).length === 0. This checks if the object has no own properties, meaning it is empty.Syntax
The common syntax to check if an object is empty is:
Object.keys(obj): Returns an array of the object's own property names..length: Gives the number of properties.- Compare with
0to see if there are no properties.
javascript
Object.keys(obj).length === 0
Example
This example shows how to check if an object is empty and prints a message accordingly.
javascript
const obj1 = {}; const obj2 = { name: 'Alice' }; function isEmpty(object) { return Object.keys(object).length === 0; } console.log(isEmpty(obj1)); // true console.log(isEmpty(obj2)); // false
Output
true
false
Common Pitfalls
Some common mistakes when checking if an object is empty:
- Using
obj === {}does not work because it compares references, not content. - Checking
obj.lengthfails because objects do not have a length property. - Not considering inherited properties;
Object.keysonly checks own properties.
javascript
const obj = {}; // Wrong way: compares references, always false console.log(obj === {}); // false // Wrong way: objects don't have length console.log(obj.length === 0); // false // Right way: console.log(Object.keys(obj).length === 0); // true
Output
false
false
true
Quick Reference
Summary tips for checking if an object is empty:
- Use
Object.keys(obj).length === 0for own properties. - Use
Object.entries(obj).length === 0as an alternative. - For deep checks, consider recursive methods (advanced).
Key Takeaways
Use Object.keys(obj).length === 0 to check if an object has no own properties.
Do not compare objects directly with === to check emptiness.
Objects do not have a length property, so that check won't work.
Object.keys only counts own properties, ignoring inherited ones.
For simple emptiness checks, Object.keys is the most reliable and readable method.