We can check if an object is empty in JavaScript by passing the object to the Object.keys()
method that returns the properties keys as an array, and checks the array length
is equal to 0.
Check if an Object is Empty in JavaScript
The simplest way to check if the object is empty in JavaScript is by using the Object.keys() method in ES5+.
- We must pass the JavaScript object to
Object.keys()
method. It will return the object keys as an array. - We can use the length property to verify if the returned array is empty or not. If the length is equal to
0
, it means the object is empty.
Let us take an example to check if object is empty in JS
const obj = {};
const obj1 = {
name: "ItsJavaScript"
}
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmpty(obj))
console.log(isEmpty(obj1))
Output
true // Length is 0 and hence the object is emtpy
false // Length is greater than 0 in this case and hence the object is not empty
Alternatively, we can also write a custom code in Javascript using a for...in
statement as shown below.
The (for...in
) statement is much faster when compared to Object.keys(obj).length
in the case of empty objects.
- The for…in statement iterates over all enumerable properties of an object
- If there are no properties and the object is empty, the iteration is stopped and returns false immediately.
- If the properties are present, then the iteration continues over all the properties and returns true.
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
const obj = {};
const obj1 = {
name: "ItsJavaScript"
}
console.log(isEmpty(obj))
console.log(isEmpty(obj1))
Output
true
false
So in the above example, even if we have a single key-value pair, the iteration happens 1-time, and we can conclude that the object is not empty.
The function can also be written with an additional check of hasOwnProperty()
method that returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
function isEmpty(obj) {
for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }
return true;
}
Check if the object is empty using JavaScript libraries.
If you are using the JavaScript libraries such as jQuery, loadash, etc, you can use the below code syntax to check whether the object is empty or not.
// jQuery
jQuery.isEmptyObject({}); // true
// loadash
_.isEmpty({}); // true
// Underscore
_.isEmpty({}); // true
// JSON.stringify
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
Conclusion
We can check if the object is empty in JavaScript by using the Object.keys()
method and by checking if the length
is equal to 0
on the array of keys returned by Object.keys()
.