isotropic-2022
Share
Blog
Search
Menu

How to Check if an Object is Empty in JavaScript

By Greg Murray
|
Last updated on April 7th, 2022
|

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?

Solution

The first step will be to create an object and add some properties to it.

const person = { name: "john doe", age: 32, };

Now that you have an object to work with you can check if it has any properties:

const properties = Object.keys(person); // ['name', 'age']

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:

const isEmpty = properties.length === 0; // false

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:

the_jserror

Let’s create a function using some of JavaScript’s newer features to safely check if an object is empty.

function isEmpty(anObject) { return !Object.keys(anObject ?? {}).length; } console.log(isEmpty({})); // true console.log(isEmpty({ key: "value" })); // false console.log(isEmpty(null)); // true

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.

Conclusion

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.

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
Greg Murray
Contributors/Editors
notloggedin
I’m a passionate and driven web developer with an eye for design and appreciation for the human aspect of technology. I am experienced with building websites for small to medium businesses or large web applications for big businesses. Websites can be custom made using cutting edge technology and responsive design or created using the website builder of your choice.
We're looking for new authors. Explore Isotropic Jobs.
Close
🇺🇸 English
Save posts, access exclusive content, join members-only communities and more.
Dark Mode Toggle
Love web dev? Join the Isotropic weekly newsletter.
cross
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
0

Your Cart is Empty