Introduction
Objects are used to store a collection of properties, each of which may be thought of as an association between a name (or key) and a value (a collection of key-value pairs).
In this guide, we will explore many JavaScript methods on how to check if an object is empty. We'll be using Vanilla JavaScript, as well as common libraries such as lodash and underscore.
When it comes to small applications that don't require external dependencies - checking whether an object is empty is best done with pure JavaScript. However, if your application already has external libraries such as lodash and underscore - they offer great ways to perform these checks as well.
Checking if an object is empty or not is a basic and frequent operation, however, there are several methods for determining whether it's empty or not.
Let's start by creating an empty Object with the object literal syntax:
const emptyObject = {}
Using the Object.keys() Method
Object.keys()
is a static method that returns an Array when we pass an object to it, which contains the property names (keys) belonging to that object. We can check whether the length
of this array is 0
or higher - denoting whether any keys are present or not. If no keys are present, the object is empty:
Object.keys(obj).length === 0 && obj.constructor === Object;
Note: The constructor check makes sure the passed argument is indeed an object.
We could also create a reusable function, if you're using the check multiple times in the project:
const isEmptyObject = (obj) => {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
console.log(isEmptyObject(emptyObject)); // true
This is by far the simplest method for determining whether an object is empty, though it's a bit verbose. We'll remove this verbosity with the following approaches - after we take a look at the Object.values()
and Object.entries()
static methods, which can be used in much the same way as Object.keys()
.
Using the Object.values() Method
Just as with keys - if an object has no values
associated (not even an undefined
/null
) - it's empty:
const isEmptyObject = (obj) => {
return Object.values(obj).length === 0 && obj.constructor === Object;
}
console.log(isEmptyObject(emptyObject)); // true
Using the Object.entries() Method
The entries()
method represents all key-value pairs (entries), which can be used as a wrapper for both of the approaches above:
const isEmptyObject = (obj) => {
return Object.entries(obj).length === 0 && obj.constructor === Object;
}
console.log(isEmptyObject(emptyObject)); // true
for...in and hasOwnProperty()
For browsers that don't support the keys()
, values()
and entries()
methods - you can explicitly loop through the properties! You can wrap this logic within a method that returns true
if no properties were found, and false
if properties were found:
const isEmptyObject = (objectName) => {
for (var prop in objectName) {
if (objectName.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
console.log(isEmptyObject(emptyObject)); // true
Using JSON.stringify
This is one of the simplest methods to use. When we stringify an object and the output is only an opening and closing bracket, we know the item is empty:
JSON.stringify(objectName) === '{}';
We could also easily be wrapped into a function:
const isEmptyObject = (objectName) => {
return JSON.stringify(objectName) === '{}';
}
console.log(isEmptyObject(emptyObject)); // true
Check if Object Is Empty With JavaScript Libraries
Libraries help us write code faster, by incorporating advanced functionality, used and honed by countless other developers, instead of writing our own solutions.
Libraries are common, typically fast/optimized, and some are present in many projects due to how useful they are. Several of them can also be used for checking whether an object is empty or not. The majority of them offer excellent compatibility for older browsers.
Using Underscore and Lodash
Both lodash and underscore are utility libraries that offer a fair bit of common utilities. They're both typically imported as _
, and can be imported via a CDN:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
Or installed a package manager such as NPM, and then imported via the require()
syntax:
$ npm install lodash
$ npm install underscore
const _ = require('lodash');
const _ = require('underscore');
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Both libraries have the exact same syntax for checking whether an object is empty:
_.isEmpty();
This function works with any data structure - lists, arrays, strings, objects, etc. The function is a wrapper around the logic that checks the length of the object that was passed in, returning true
or false
:
_.isEmpty(emptyObject); // true
jQuery
jQuery is a popular JavaScript library, present in many projects around the world. Due to its light weight and features that expand the scope of JavaScript's built-in capabilities - it's become a staple.
jQuery can be imported via a CDN:
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
Or installed a package manager such as NPM, and then imported via the require()
syntax:
$ npm install jquery
It's typically imported as $
:
const $ = require('jquery');
Naturally, you can use it to check whether an object is empty or not:
$.isEmptyObject(emptyObject); // true
Ramda
Ramda is a functional JavaScript library! It never mutates data and supports the creation of purely functional pipelines. For those with a more functional programming background - it's a great library to feel at home with.
Ramda can be imported via a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js"></script>
Or installed a package manager such as NPM, and then imported via the require()
syntax:
$ npm install ramda
It's typically imported as R
:
const R = require('ramda');
If you're already using it - it offers an isEmpty()
function as well:
R.isEmpty(emptyObject); // true
Hoek
@hapi/hoek is part of the hapi ecosystem, and a popular utility method library for hapi-based apps. It offers a deepEqual()
method, that checks whether two objects are the same (depth-wise):
Hoek.deepEqual({}, emptyObject); // true
Conclusion
In this article, we have taken a look at how to check whether an object is empty or not in JavaScript. To this end - we've used several Vanilla JS approaches, jQuery, Underscore, Lodash, Ramda, Hoek and the JSON module.