Code Snippets
/

Check if an Object is Empty

Check if an Object is Empty

Checking whether an object has any keys is one of those `if (!obj)` traps that bites every JavaScript codebase. This snippet covers the canonical short-circuit, the reason `Object.keys().length === 0` works, and an `isEmpty` helper that handles arrays, strings, Maps, Sets, and plain objects in one pass. Drop it next to your other guards so empty checks stop returning surprises.

JavaScript
Easy
3 snippets
utility
code-template

665 views

18

function isEmptyObject(obj) {
    return obj != null && typeof obj === 'object' && Object.keys(obj).length === 0;
}

console.log(isEmptyObject({}));        // true
console.log(isEmptyObject({ a: 1 }));  // false
console.log(isEmptyObject(null));      // false
console.log(isEmptyObject(undefined)); // false
console.log(isEmptyObject('hello'));   // false (a string is not an object)

Object.keys(obj).length === 0 is the safest plain-object emptiness check in modern JavaScript: it inspects only own enumerable string keys, which matches what JSON serialisation cares about. The obj != null && typeof obj === 'object' guard rejects null, undefined, primitives, and arrays-or-string thrown at it by accident. The cost is one transient array allocation; for steady-state hot paths see the next accordion. This is the version to default to in app code.