One thing that is enjoyable about writing JavaScript code is how simple it is to create and use objects. There are so many creative uses for these objects beyond simply storing and retrieving keyed values.
Something that is common amongst the uses of objects, though, is the need to easily check if an object is empty. In other words, how can you tell if an object has any defined properties?
The first step will be to create an object and add some properties to it.
Now that you have an object to work with you can check if it has any properties:
Objects have many useful methods you can use and in this case we use the Object.keys()
method which simply returns an array containing all of the property names that the object has. Now just check if the length of that array is 0:
That’s pretty much it but there is potentially one issue. If you try this using an object that is undefined
or null
you will get an error:
Let’s create a function using some of JavaScript’s newer features to safely check if an object is empty.
There are a few things to note here. Rather than checking if the length of the object’s array of keys is 0, you can just use the value of its length plus the !
operator to effectively change it into a boolean. Since 0 is falsy and any other value for the length is truthy, you will get your desired boolean value which in this case is true if the object is empty and false if it isn’t. You can use !!
instead if you want to switch the function around to determine if an object is not empty.
The other interesting piece here is the usage of the nullish coalescing operator ??
. This operator was introduced in ECMAScript 2020 and has similar behavior to the ||
operator but without the possibility of unintended results. Use the ??
here to make sure there are no errors thrown if the given object is null
or undefined
.
The ??
operator only returns the right-hand side of the expression if the left-hand side is null
or undefined
whereas the ||
operator will return the right-hand side if the left-hand side is any falsy value.
There you have it! This is a simple yet effective way to check if an object is empty in JavaScript. You can use the isEmpty
function above to safely check whether or not an object is empty or use the more direct Object.keys().length
method if you are not worried about the object potentially being null
or undefined
. Either way, the strategy is simple.
Get the keys of the given object and, if there are none, the object must be empty. Pick whatever method works best for you and your codebase and, as always, feel free to leave a comment if you find this useful or have any suggestions on a better way to do this.