What is the safest way to check if a JavaScript object is completely empty? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
12 days ago

What is the safest way to check if a JavaScript object is completely empty?

message-square
0

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 '