In JavaScript, you can use various methods to check if an object is empty.
Here are three of my favorites.
Using the Object.keys()
Method
The Object.keys()
method returns an array of strings representing the keys contained within the object.
Technically speaking, if the length of this array equals 0, then the object itself is empty.
Here’s how you can test for this:
function isEmpty(myObject) {
return Object.keys(myObject).length === 0;
}
This function will return true
or false
depending on whether the object is empty or not.
Using the Object.entries() Method
The Object.entries()
method returns an array containing an object’s key/value pairs. (It’s similar to the Object.keys()
method described above, but it returns the key/value pairs rather than just the keys.)
By checking the length of this array, you can also determine if the object is empty.
function isEmpty(myObject) {
return Object.entries(myObject).length === 0;
}
Once again, this function will return true
if myObject
is empty, and false
if it isn’t.
Using a for...in
Loop
Now let’s try inverse reasoning to solve this problem using a for...in
loop.
function isEmpty(myObject) {
for (let key in myObject) {
if (myObject.hasOwnProperty(key)) {
return false;
}
}
return true;
}
See what we did there?
This method iterates over the object’s properties using a for...in
loop and checks if any property is directly defined on the object (excluding any properties inherited from the prototype chain).
If it finds any property, then the object is not empty.