Link to code snippet: GitHub
Working with objects always feels slightly less fluid when compared to arrays. With arrays, we can simply validate the length of the array (if it's equal to zero). For objects, we can do something similar thanks to the built-in Object.keys()
method, but even then we need to add an extra validation. Let's take a closer look at two different ways to check for empty objects.
Set the Scene
Let's create two test objects that we'll use to perform our validations. The first object will have three properties and the second object will have none.
const object1 = { a: 5, b: 8, c: 10 }
const object2 = {}
Method 1: Object.keys()
The first method we'll use involves a combination of Object.keys()
and checking whether the constructor is an extension of the Object class. The latter is important because in JavaScript, we can create new object instances in many different ways. For example, new Date()
and new Array()
would both pass the Object.keys()
validation, but we want to make sure that we're actually testing objects and not primitives or wrapper instances.
const isObject1Empty =
Object.keys(object1).length === 0 && object1.constructor === Object
console.log(isObject1Empty) // false
const isObject2Empty =
Object.keys(object2).length === 0 && object2.constructor === Object
console.log(isObject2Empty) // true
Method 2: for...in loop
The second method is the old-fashioned way: a for...in loop. This method loops over each object property and calls hasOwnProperty()
to verify whether the specified property is a direct property of the object. If the object has a property, the result of the function will false (meaning not empty).
const isEmpty = object => {
for (let prop in object) {
if (object.hasOwnProperty(prop)) {
return false
}
}
return true
}
console.log(isEmpty(object1)) // false
console.log(isEmpty(object2)) // true
Method 3: JSON.stringify()
The final method we can use to validate empty objects is a rather interesting approach. We can use JSON.stringify()
to convert JavaScript objects into JSON strings. If we do this for our two objects and compare each of them to an empty object (after converting to a JSON string), we can see that the first object is not empty and the second one is.
console.log(JSON.stringify(object1) === JSON.stringify({})) // false
console.log(JSON.stringify(object2) === JSON.stringify({})) // true
As always, it's a good practice to create helper utility functions that can be easily reused throughout your application. This is a prime example of a use case you will run into fairly often. There are also utility libraries (e.g. Lodash) that can be used as well.