In this article you will learn five different ways to check if an object is empty in JavaScript. Let’s jump right in.
How to Check If an Object Is Empty in JavaScript
- Use Object.keys
- Loop Over Object Properties With for…in
- Use JSON.stringify
- Use jQuery
- Use Underscore and Lodash Libraries
1. Use Object.keys
Object.keys
will return an array, which contains the property names of the object. If the length of the array is 0
, then we know that the object is empty.
function isEmpty(obj) {
return **Object.keys(obj).length === 0**;
}
We can also check this using Object.values
and Object.entries
. This is typically the easiest way to determine if an object is empty.
2. Loop Over Object Properties With for…in
The for…in
statement will loop through the enumerable property of the object.
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
In the above code, we will loop through object properties and if an object has at least one property, then it will enter the loop and return false. If the object doesn’t have any properties then it will return true.
3. Use JSON.stringify
If we stringify the object and the result is simply an opening and closing bracket, we know the object is empty.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}'
}
4. Use jQuery
jQuery.isEmptyObject(obj);
5. Use Underscore and Lodash Libraries
_.isEmpty(obj);
These five quick and easy ways to check if an object is empty in JavaScript are all you need to get going.