For JavaScript objects, there is no built-in .length
or .isEmpty
method available to check if they are empty.
Here are 4 different methods that you can use to make sure that a given object does not have its own properties:
Object.entries()
Method
The Object.entries()
method takes an object as an argument and returns an array of its enumerable property [key, value]
pairs.
We can then use the .length
property of the array to check if it contains any item:
const user = {}
Object.entries(user).length === 0 // true
const bird = {
name: 'Penguin',
avatar: '🐧'
}
Object.entries(bird).length === 0 // false
Note:
Object.entries()
only works in modern browsers and is not supported by IE. If you need backward compatibility, consider adding a polyfill or useOject.keys()
method instead.
Object.keys()
Method
The Object.keys()
method is the best way to check if an object is empty because it is supported by almost all browsers, including IE9+.
It returns an array of a given object's own property names. So we can simply check the length of the array afterward:
Object.keys({}).length === 0 // true
Object.keys({ name: 'Atta' }).length === 0 // false
Object.getOwnPropertyNames()
Method
The Object.getOwnPropertyNames()
method takes an object as parameter and returns an array of its own property names:
Object.getOwnPropertyNames({}).length === 0 // true
Object.getOwnPropertyNames({ id: 1, name: 'John Doe' }).length === 0 // false
3rd-Party Libraries
If you are already using 3rd-party libraries like jQuery or Lodash in your web application, you can also use them to check if an object is empty:
// jQuery
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ id: 1, name: 'John Doe' }) // false
// Lodash
_.isEmpty({}) // true
_.isEmpty({ name: 'Emma' }) // false
Prototype Function
You can write a helper function isEmpty()
and add it to the object's prototype:
Object.prototype.isEmpty = function () {
return Object.keys(this).length == 0
}
Now you can call the isEmpty()
method on any JavaScript object to check if it has its own properties:
const obj = {}
obj.isEmpty() // true
const site = {
title: 'Twitter',
website: 'https://twitter.com'
}
site.isEmpty() // false
Be careful while extending the Object
prototype, as it can cause issues when used together with other JavaScript frameworks. Instead, use the Object.keys()
method in JavaScript applications to check if an object is empty.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.