In this short tutorial we are going to explore some options and examples for testing Javascript objects for the empty condition.
There are times when working with objects the returned object will come as:
var object= {};
This could happen when working with modules that pass data from a server to server, it might be the response of an API or backend service etc, so it’s handy to know in which way Javascript can check if object is empty.
Checking for empty objects in Javascript is easy, let’s jump into it.
Pre-ECMA 5:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return JSON.stringify(obj) === JSON.stringify({});
}
jQuery.isEmptyObject({}); // true
_.isEmpty({}); // true
_.isEmpty({}); // true
Hoek.deepEqual({}, {}); // true
Ext.Object.isEmpty({}); // true
angular.equals({}, {}); // true
R.isEmpty({}); // true
Example 2:
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
If ECMAScript 5 support is available, you can use Object.keys() instead:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
Additional resources:
Get the book: Javascript snipets
Other Dev posts:
Discussion (1)
It's not correct, Object.keys returns only enumerable properties of objects.