This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
In this quick article, I’ll show you how you can check if an object is empty in JavaScript.
In your day-to-day JavaScript development, you might need to check if an object is empty or not. And if you’ve had to do this, you probably know that there’s no single direct solution. However, there are different techniques that you can use to create a custom solution for your own use case. Apart from that, if you’re using a JavaScript utility library in your project, there’s a chance that it already provides a built-in method to check if an object is empty.
The Modern Way (ES5+)
In this section, we’ll discuss the different methods that you could use in modern browsers that support the ES5 edition.
1. The Object.keys()
Method
The Object.keys()
method returns an array of enumerable property names of a given object. And thus, we can use it to check if an object has any properties by counting the length of this array.
Let’s have a look at the following example.
function isEmptyObject(obj) { return Object.keys(obj).length === 0; } console.log(isEmptyObject({})); // output: true var bar = {"foo": "1"}; console.log(Object.keys(bar).length); // output: 1 console.log(isEmptyObject(bar)); // output: false
As you can see in the above example, the bar
object has the foo
property attached to it, and thus the bar.keys(obj).length
expression would return a value greater than zero. So the isEmptyObject
function would return false
in this case.
Go ahead and test the isEmptyObject
function with different values.
Note that the Object.keys()
method can return some surprising results for special types. For example, isEmptyObject
will return true for a Date
or RegExp
object.
console.log(isEmptyObject(Date.now())); //output: true console.log(isEmptyObject(new RegExp())); //output: true
Also, be careful because calling this method with a null
or undefined
value. They would result in an exception. Later on we'll create a bullet-proof solution that won't fail on a null input.
console.log(isEmptyObject(null)); //throws Uncaught TypeError: Cannot convert undefined or null to object
2. The Object.getOwnPropertyNames()
Method
The Object.getOwnPropertyNames()
method returns an array of all the properties of a given object. Although it may look identical to the Object.keys()
method, there’s a difference. The Object.getOwnPropertyNames()
method also considers the non-enumerable properties, while the Object.keys()
only considers enumerable properties. Most of the time these will be equivalent, but there is a risk that Object.keys()
will miss certain properties that have been declared not to be enumerable.
Let’s go through the following example.
function isEmptyObject(obj) { return Object.getOwnPropertyNames(obj).length === 0; } console.log(isEmptyObject({})); // output: true var bar = {"foo": "1"}; console.log(Object.getOwnPropertyNames(bar).length); // output: 1 console.log(isEmptyObject(bar)); // output: false
As you can see, testing emptiness with Object.getOwnPropertyNames()
works similarly to using Object.keys()
.
The edge cases are a bit different though—the Object.getOwnPropertyNames()
method will still return true for a Date
, but will return false for a RegExp
.
console.log(isEmptyObject(Date.now())); //output: true console.log(isEmptyObject(new RegExp()); //output: false
Once again, this method will fail on a null
or undefined
input.
3. JSON.stringify
The JSON.stringify
method is used to convert a JavaScript object to a JSON string. So we can use it to convert an object to a string, and we can compare the result with {}
to check if the given object is empty.
Let’s go through the following example.
function isEmptyObject(obj){ return JSON.stringify(obj) === '{}'; } console.log(isEmptyObject({})); // output: true var bar = {"foo":"1"}; console.log(JSON.stringify(bar)); // output: {"foo":"1"} console.log(isEmptyObject(bar)); // output: false
Once again the edge cases are a bit different. JSON.stringify
will return a numeric string like "1651283138454"
for a Date, but will return an empty object for a RegExp
. So using the JSON.stringify
method gives exactly the opposite results for these classes to the Object.getOwnPropertyNames
method!
console.log(isEmptyObject(Date.now())); //output: false console.log(isEmptyObject(new RegExp()); //output: true
Another twist is that the JSON.stringify
method won't throw an exception on a null input. Instead it will return false
which might not be what you would expect.
console.log(isEmptyObject(null)); //output: false
4. Object.entries()
The Object.entries()
method returns an array of arrays, with each element being an array of key-value pairs of an object’s property.
Let’s go through the following example to understand how it works exactly.
function isEmptyObject(obj) { return Object.entries(obj).length === 0; } console.log(isEmptyObject({})); // output: true var bar = {"foo":"1"}; console.log(Object.entries(bar)); // output: [['foo', '1']] console.log(Object.entries(bar).length); // output: 1 console.log(isEmptyObject(bar)); // output: false
As you can see, the Object.entries()
method converts an object into an array, and we can count the length of that array to check if the object in question is empty.
This is very similar to the Object.keys()
method and will give the same results on our edge case examples of Date
and RegExp
objects. It will also throw an exception for a null
or undefined
input.
console.log(isEmptyObject(Date.now())); //output: true console.log(isEmptyObject(new RegExp())); //output: true
A Bullet-Proof Solution
A problem with the simple solutions above is that they give inconsistent results for edge cases: special objects like RegExp
or Date
, null
or undefined
values, or primitives like integers. Here's a simple but more bullet-proof solution.
function isEmptyObject(value) { const type = typeof value const isObject = value != null && type === 'object' return isObject && Object.keys(value).length === 0; }
This method does exactly what it says: it returns true exactly if the input value is both an object and is empty. It will work with null and undefined values—returning false because these are not objects. For special objects like Date
and RegExp
it will return true because they don't have any special keys defined. It will also return true for an empty array and false
for a non-empty array.
The Pre-ES5 Way
In this section, we’ll discuss a solution which would work even with older browsers. This was used frequently until the JavaScript ES5 era, when there were no built-in methods available to check if an object is empty.
Let’s go through the following example.
function isEmptyObject(obj) { for (var property in obj) { if (obj.hasOwnProperty(property)) { return false; } } return true; } console.log(isEmptyObject({})); // output: true console.log(isEmptyObject({"foo":"1"})); // output: false
In the above example, we’ve built a custom function which you can call to check if an object is empty. It takes a single argument, and you need to pass an object which you want to test. In the isEmptyObject
function, we try to iterate over the object properties. If the object has any properties, we’ll return FALSE
, otherwise we’ll return TRUE
.
You can go ahead and test the isEmptyObject
function with different values. As shown in the above example, we’ve called it with different values and logged the output with the console.log
function.
So that’s how you can check if an object is empty in browsers that don’t support the ES5 edition. In the next section, we’ll discuss it in the context of modern browsers.
The jQuery Way
If you’re already using the jQuery library in your project, it’s really easy to check if an object is empty, since the jQuery library already provides the isEmptyObject
method, which allows you to check if an object is empty.
Let’s quickly go through the following example.
jQuery.isEmptyObject({}); // true jQuery.isEmptyObject({"foo":"1"}); // false
As you can see, it’s fairly straightforward to use the isEmptyObject
method with jQuery.
Similarly, the Lodash and Underscore.js libraries have _.isEmpty()
.
Conclusion
In this article, we discussed a number of different ways to check if an object is empty or not in JavaScript. Check out some of our other tutorials about JavaScript programming!
- HTML519 Best HTML5 and JavaScript Game Engines and Templates
- HTML515 Best HTML5 and JavaScript Video Players (+5 Best Free Players)
- JavaScriptHow to Use Map, Filter, and Reduce in JavaScript
- JavaScriptHow to Create a JavaScript PDF Viewer
- JavaScriptHow to Create a JavaScript PDF Viewer
This post has been updated with contributions from Neema Muganga.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Sajal Soni
Sajal Soni | Sciencx (2021-05-24T04:59:32+00:00) How to Check if an Object Is Empty in JavaScript. Retrieved from https://www.scien.cx/2021/05/24/how-to-check-if-an-object-is-empty-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.