Skip to content
VersionSize

isEmpty

The isEmpty utility checks if a given value is considered "empty". It supports a wide variety of data types, including strings, arrays, objects, Maps, and Sets.

Implementation

View Source Code
ts
import { isArray } from './isArray';
import { isNil } from './isNil';
import { isObject } from './isObject';

/**
 * Checks if the given argument is empty.
 *
 * @example
 * ```ts
 * isEmpty(null); // true
 * isEmpty(undefined); // true
 * isEmpty([]); // true
 * isEmpty({}); // true
 * isEmpty(''); // true
 * isEmpty(0); // false
 * isEmpty(123); // false
 * isEmpty('abc'); // false
 * isEmpty([1, 2, 3]); // false
 * isEmpty({ a: 1, b: 2 }); // false
 * ```
 *
 * @param arg - The argument to be checked.
 *
 * @returns `true` if all arguments are `null`, `undefined`, `{}`, `[]`, or empty strings. Otherwise, it returns `false`.
 */
// biome-ignore lint/suspicious/noExplicitAny: -
export function isEmpty(arg: any): boolean {
  if (isNil(arg) || arg === '') return true;
  if (isArray(arg)) return arg.length === 0;
  if (arg instanceof Map || arg instanceof Set) return arg.size === 0;
  if (isObject(arg)) return Object.keys(arg).length === 0;
  return false;
}

export const IS_EMPTY_ERROR_MSG = 'Expected an empty value';

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Versatile: Handles strings (length 0), arrays (length 0), objects (no enumerable keys), and collection types (size 0).
  • Safe: Properly handles null and undefined (considering them empty).

API

ts
function isEmpty(value: unknown): boolean;

Parameters

  • value: The value to check for emptiness.

Returns

  • true if the value is empty; otherwise, false.

Examples

Checking Collections

ts
import { isEmpty } from '@vielzeug/toolkit';

isEmpty([]); // true
isEmpty([1, 2, 3]); // false

isEmpty(new Set()); // true
isEmpty(new Map()); // true

Checking Strings & Objects

ts
import { isEmpty } from '@vielzeug/toolkit';

isEmpty(''); // true
isEmpty('hello'); // false

isEmpty({}); // true
isEmpty({ a: 1 }); // false

Checking Nullable Values

ts
import { isEmpty } from '@vielzeug/toolkit';

isEmpty(null); // true
isEmpty(undefined); // true

Implementation Notes

  • For objects, it checks for own enumerable property names using Object.keys().
  • For Map and Set, they are treated as objects. An empty Map or Set will return true since Object.keys() returns an empty array for them.
  • For all other types (numbers, booleans, etc.), it returns false unless the value is null or undefined.

See Also

  • isNil: Check if a value is strictly null or undefined.
  • isDefined: Check if a value is not null or undefined.
  • isArray: Check if a value is an array.