Check if a given object is empty without considering any custom props defined by prototype.
Consider this sample object -
const earth = {};
Use Object.entries() or equivalent
Object.entries gives us a short way to access entries in an array form. We could just check whether entries are empty to decide whether the parent object is empty.
const earth = {};
const isEmpty = !Object.entries(earth).length;
console.log(isEmpty);
// true
The above logic is unaffected even if the object has defined properties.
const earth = {};
Object.defineProperty(earth, "life", Boolean);
const isEmpty = !Object.entries(earth).length;
console.log(isEmpty);
// true
You could also use comparable functions that retrieve keys or values from an object.
const earth = {};
console.log(Object.values(earth).length);
// 0
console.log(Object.keys(earth).length);
// 0
Use a custom function with hasOwnProperty
To check if earth is empty, you can just do -
console.log(isEmpty(earth)); // true
function isEmpty(obj) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) return false;
// alternative: define prop as not enumerable and don't use hasOwnProperty
}
return true;
}
If the object is not empty..
const earth = { name: "earth", position: 3 };
console.log(isEmpty(earth)); // false
What not to do?
Note that you cannot check the object directly to check a truthy condition.
const earth = new Object();
if (earth) console.log("earth is not empty");
// earth is not empty
const mars = { population: 1 };
console.log("Mars is empty: ", !!mars); // true
Recommendation
Use Object.entries() to check empty conditions unless you really are in love with loops.
Already have an object? Check how you can empty an object in Javascript :)