Skip to content

isEmpty function ​

Checks whether a container holds nothing: an empty string, array, Map, Set or object. null and undefined count as empty.

ts
import { isEmpty } from 'utils';

Signature ​

ts
export function isEmpty(value: unknown): boolean

Parameters ​

NameDescription
valueThe value to check.

Returns ​

true for an empty container, null or undefined; false for a number or a boolean.

Example ​

ts
isEmpty({}); // true
isEmpty([0]); // false
isEmpty(new Map()); // true

Tests ​

Line coverage: 100 %.

  • ✅ finds undefined empty
  • ✅ finds undefined empty
  • ✅ finds "" empty
  • ✅ finds undefined empty
  • ✅ finds {} empty
  • ✅ finds {} empty
  • ✅ finds {} empty
  • ✅ finds {} empty
  • ✅ finds " " not empty
  • ✅ finds 0 not empty
  • ✅ finds {} not empty
  • ✅ finds {} not empty
  • ✅ finds {} not empty
  • ✅ finds {"0":0} not empty
  • ✅ finds 0 not empty
  • ✅ finds false not empty
  • ✅ finds undefined not empty

Source ​

src/object/is-empty.ts (on GitHub)

Source code
ts
/**
 * Checks whether a container holds nothing: an empty string, array, `Map`, `Set` or object. `null` and
 * `undefined` count as empty.
 *
 * @param value - The value to check.
 * @returns `true` for an empty container, `null` or `undefined`; `false` for a number or a boolean.
 * @example
 * isEmpty({}); // true
 * isEmpty([0]); // false
 * isEmpty(new Map()); // true
 */
export function isEmpty(value: unknown): boolean {
  if (value === null || value === undefined) {
    return true;
  }
  if (typeof value === 'string') {
    return value.length === 0;
  }
  if (typeof value !== 'object') {
    return false;
  }
  if (value instanceof Map || value instanceof Set) {
    return value.size === 0;
  }
  return (
    (Array.isArray(value) || ArrayBuffer.isView(value) ? Reflect.get(value, 'length') : Object.keys(value).length) === 0
  );
}
Test file
ts
import { isEmpty } from './is-empty';

describe(isEmpty, () => {
  it.for([null, undefined, '', [], {}, new Map(), new Set(), new Float64Array(0)])('finds %j empty', (value) => {
    expect(isEmpty(value)).toBe(true);
  });

  it.for([' ', [0], { a: undefined }, new Map([[1, 1]]), new Set([0]), new Uint8Array(1), 0, false, (): number => 0])(
    'finds %j not empty',
    (value) => {
      expect(isEmpty(value)).toBe(false);
    },
  );
});

Keywords: is, empty, objects, function

Generated from the JSDoc of the sources.