
How to Check If an Object Is Empty in JavaScript Safely
Check for an empty object with Object.keys(obj).length === 0 after guarding null. See symbol keys, inherited properties, Date and Map traps and for in.
Tag
5 posts

Check for an empty object with Object.keys(obj).length === 0 after guarding null. See symbol keys, inherited properties, Date and Map traps and for in.

Object.defineProperty() sets a property and its attributes: writable, enumerable, configurable, getters and setters. See the defaults that catch people out.

Compare objects by content with isDeepStrictEqual or a recursive function that handles key order, NaN, dates, maps and cycles. See why JSON.stringify fails.

Object.setPrototypeOf() changes the prototype of an existing object. See its errors, the cycle check, null prototypes and when Object.create wins.

Use Object.hasOwn(obj, key) for own keys and the in operator to include inherited ones. See why comparing to undefined fails, and Map lookups for user keys.