JavaScript Snippet

Check if an Object is Empty

Difficulty: Easy

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.

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

664 views

18

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.