snippetjavascriptCritical
How do I test for an empty JavaScript object?
Viewed 0 times
emptyobjecthowfortestjavascript
Problem
After an AJAX request, sometimes my application may return an empty object, like:
How can I check whether that's the case?
var a = {};How can I check whether that's the case?
Solution
You can use a for…in loop with an
If you also need to distinguish
Note that comparing against
Do not use
For compatibility with JavaScript engines that don’t support ES 2022+,
Many popular libraries also provide functions to check for empty objects:
jQuery:
lodash:
Underscore:
Hoek:
ExtJS:
AngularJS (version 1):
Ramda:
Object.hasOwn (ECMA 2022+) test to check whether an object has any own properties:function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}If you also need to distinguish
{}-like empty objects from other objects with no own properties (e.g. Dates), you can do various (and unfortunately need-specific) type checks:function isEmptyObject(value) {
if (value == null) {
// null or undefined
return false;
}
if (typeof value !== 'object') {
// boolean, number, string, function, etc.
return false;
}
const proto = Object.getPrototypeOf(value);
// consider Object.create(null), commonly used as a safe map
// before Map support, an empty object as well as {}
if (proto !== null && proto !== Object.prototype) {
return false;
}
return isEmpty(value);
}
Note that comparing against
Object.prototype like in this example will fail to recognize cross-realm objects.Do not use
Object.keys(obj).length. It is O(N) complexity because it creates an array containing all the property names only to get the length of that array. Iterating over the object accomplishes the same goal but is O(1).For compatibility with JavaScript engines that don’t support ES 2022+,
const can be replaced with var and Object.hasOwn with Object.prototype.hasOwnProperty.call:function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true
}Many popular libraries also provide functions to check for empty objects:
jQuery:
jQuery.isEmptyObject({}); // truelodash:
_.isEmpty({}); // trueUnderscore:
_.isEmpty({}); // trueHoek:
Hoek.deepEqual({}, {}); // trueExtJS:
Ext.Object.isEmpty({}); // trueAngularJS (version 1):
angular.equals({}, {}); // trueRamda:
R.isEmpty({}); // trueCode Snippets
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true
}jQuery.isEmptyObject({}); // true_.isEmpty({}); // true_.isEmpty({}); // trueContext
Stack Overflow Q#679915, score: 7556
Revisions (0)
No revisions yet.