Description
isEmpty
returns true
if the provided value is null
or undefined
, or if itโs an object (including arrays)
with zero own enumerable keys. Otherwise, it returns false
.
Code Byte
export const isEmpty = (val: any): boolean => {
return val == null || (typeof val === 'object' && Object.keys(val).length === 0);
}
Use cases:
- Input validation: Quickly check if an object or array has any data before processing.
- Form handling: Skip submission or show warnings when required fields are empty.
- API responses: Guard against empty payloads before rendering UI.
- Default values: Fall back to defaults when objects are empty.
Example usage:
import { isEmpty } from './is-empty.util';
console.log(isEmpty(null)); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty({ foo: 1 })); // false
console.log(isEmpty([1, 2, 3])); // false