Skip to main content

isEmpty

TS JS Deno

Returns true if the a value is an empty object, collection, has no enumerable properties or is any type that is not considered a collection.

Check if the provided value is null or if its length is equal to 0.

typescript
const isEmpty = (val: any) => val == null || !(Object.keys(val) || val).length;

// If typescript compiler is yelling because of the type `any`
const isEmpty = (val: Record<string, unknown> | null | undefined) =>
val == null || !(Object.keys(val) || val).length;
typescript
isEmpty([]); // true
isEmpty({}); // true
isEmpty(""); // true
isEmpty([1, 2]); // false
isEmpty({ a: 1, b: 2 }); // false
isEmpty("text"); // false
isEmpty(123); // true - type is not considered a collection
isEmpty(true); // true - type is not considered a collection