isEmptyObject
Checks if a value is a plain object with no own enumerable properties.
1/**
2 * Checks if a value is a plain object with no own enumerable properties.
3 *
4 * @param obj - The object to check.
5 * @returns True if the object is empty, false otherwise.
6 */
7export function isEmptyObject(obj: unknown): boolean {
8 return (
9 obj !== null &&
10 typeof obj === 'object' &&
11 obj.constructor === Object &&
12 Object.keys(obj).length === 0
13 );
14}
Strict Type Checking
Verifies that the input is a non-null, plain object — not an array, function, or instance of a custom class.
Safe and Predictable
Prevents false positives by explicitly checking for
Object
constructor and own enumerable keys.Lightweight Implementation
Uses minimal logic with native JavaScript methods, ensuring fast execution and easy comprehension.
Tests | Examples
1test('isEmptyObject - returns true for empty plain object', () => {
2 expect(isEmptyObject({})).toBe(true);
3});
4
5test('isEmptyObject - returns false for object with keys', () => {
6 expect(isEmptyObject({ a: 1 })).toBe(false);
7});
8
9test('isEmptyObject - returns false for arrays', () => {
10 expect(isEmptyObject([])).toBe(false);
11});
12
13test('isEmptyObject - returns false for null', () => {
14 expect(isEmptyObject(null)).toBe(false);
15});
16
17test('isEmptyObject - returns false for non-object values', () => {
18 expect(isEmptyObject(42)).toBe(false);
19 expect(isEmptyObject('string')).toBe(false);
20 expect(isEmptyObject(true)).toBe(false);
21});
22
23test('isEmptyObject - ignores inherited properties', () => {
24 const proto = { x: 1 };
25 const obj = Object.create(proto);
26 expect(isEmptyObject(obj)).toBe(true);
27});
Common Use Cases
Validation Logic
Determine if a config, form, or API response contains any meaningful values.
Conditional Rendering
Conditionally show fallback UI when data objects are empty.
State Cleanup Checks
Detect and handle cases where a state object has been reset or cleared.
Serialization Decisions
Avoid sending empty objects in payloads when constructing JSON or API requests.
Logging and Debugging
Skip verbose or redundant logs by filtering out empty structures.