In JavaScript, testing if an object is an empty object literal {} can be done in different ways. Here's a simple function to check if a given object is empty (has no own enumerable properties):
Object.keys() returns an array of a given object's own enumerable property names. If the length of this array is zero (0), and the object's constructor is Object, it means the object has no own enumerable properties and is an empty object literal {}.
However, this function might not work as intended if the object has non-enumerable properties or if the object's prototype chain has been modified. To account for non-enumerable properties as well, you can use Object.getOwnPropertyNames() instead:
Keep in mind that these methods will consider an object with non-enumerable properties as not empty. If you want to check for any properties, including non-enumerable and inherited properties, you would need to check the object more thoroughly:
function isEmpty(obj) {
for (let prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return obj.constructor === Object;
}
// Usage examples
console.log(isEmpty({})); // true
console.log(isEmpty({ a: 1 })); // false
This function uses a for...in loop to enumerate all properties of the object, including inherited properties, but only considers the object non-empty if it has its own properties. This is checked with Object.prototype.hasOwnProperty.call(obj, prop) to ensure that the property is not inherited.
Evaluation of object emptiness can be situational and based on specific requirements like considering non-enumerable, inherited, or prototype properties. Choose the method that best fits your use case.