How to Check for an Empty Object in JavaScript
You might encounter a situation where you need to check if an object is empty, meaning it doesn't have any properties or keys.
Let's dive into a simple method to do just that.
Using Object.keys()
The easiest way is to use the built-in method Object.keys()
, which gives us an array of an object's own property names.
For an empty object, this array will be empty. So, one way to check if an object is empty is to see if the length of this array is 0
:
const obj = {}; if (Object.keys(obj).length === 0) { console.log('The object is empty'); } else { console.log('The object is not empty'); }
Avoiding False Positives
While the above method works for most cases, it can sometimes give false positives.
To ensure our check is accurate, we add another condition: obj.constructor === Object
. This ensures that our object is a plain object and not an instance of another class or type.
const obj = {}; if (Object.keys(obj).length === 0 && obj.constructor === Object) { console.log('The object is empty'); } else { console.log('The object is not empty'); }
Why the Extra Check?
Imagine you have a custom class:
function MyClass() {} const myInstance = new MyClass();
For myInstance
, Object.keys(myInstance).length
would be 0
because it has no properties. But it's not a plain empty object; it's an instance of MyClass
. By checking its constructor, we can differentiate between plain objects and other types or class instances.