JavaScript has no built-in .length
or .isEmpty
methods for objects to check if they are empty. So we have to create our own utility method or use 3rd-party libraries like jQuery or Lodash to check if an object has own properties.
Here are some of the methods you can use to make sure that a given object does not have its own properties:
Object.entries()
Method
The ES8 method Object.entries()
takes an object as argument and returns an array of its enumerable property [key, value]
pairs. We can then use .length
method of the array to check if it contains any property:
const user = {};
Object.entries(user).length === 0; // true
const bird = {
name: 'Penguin',
avatar: '🐧'
};
Object.entries(bird).length === 0; // false
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 probably 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
Similar to Object.keys()
method, the Object.getOwnPropertyNames()
method also 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
Alternatively, you can write a helper function isEmpty()
and add it to Object
prototype:
Object.prototype.isEmpty = function () {
return Object.keys(this).length == 0;
}
Now you can just call isEmpty()
method on any JavaScript object to check if it has 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 some issues when used together with other JavaScript frameworks. It is best to use the Object.keys()
method in vanilla JavaScript applications.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.