What is the safest way to check if a JavaScript object is completely empty?
Verify that the value is a non-null plain object and check **Object.keys(obj).length === 0** (or **Reflect.ownKeys(obj).length === 0** if you also want to check non-enumerable and Symbol` keys).
Safe Empty Object Check (Recommended)
function isEmptyObject(obj) {
return (
obj !== null &&
typeof obj === "object" &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0
);
}
console.log(isEmptyObject({})); // true
console.log(isEmptyObject({ a: 1 })); // false
console.log(isEmptyObject(null)); // false
console.log(isEmptyObject([])); // false '
You must log in or register to comment.
