← Daily Logs
GreatFrontEnd

Implement isEmpty

MediumJul 2, 2026lodashtype-checkscollections

Almost the same type-dispatch as `size` from earlier — arrays and strings check `.length`, `Map`/`Set` check `.size`, plain objects check their key count — except every non-collection value (numbers, booleans, symbols, regexes, `null`) is defined as empty by fiat, which turns out to fall out of the same branches for free.

The problem

Implement `isEmpty(value)` returning whether it has zero items: arrays/strings with `.length === 0`, `Map`/`Set` with `.size === 0`, plain objects with no own enumerable properties, and any non-collection value (`null`, booleans, numbers, symbols, regexes) treated as empty regardless of its own contents.

The regex case looks like it needs a special rule — `isEmpty(/abc/)` should be `true` even though the pattern clearly isn't 'empty' in a colloquial sense — but the spec's real definition is 'no own enumerable properties to inspect,' and a `RegExp` instance genuinely has none (its `lastIndex` property is non-enumerable), so no special-case is actually required.

The approach

Reuse the same shape as `size`: guard `value == null` first, then branch on `Array.isArray(value) || typeof value === 'string'` for `.length`, then `instanceof Map || instanceof Set` for `.size`, then fall through to `typeof value === 'object'` and count `Object.keys(value).length`.

The difference from `size` is only the base case. `size` returns `0` for anything unsupported; `isEmpty` needs `true` for the exact same set of values, so the final fallthrough (past every collection check) becomes a bare `return true` instead of `return 0` — every non-collection value is 'empty' by definition, which is precisely what falling off the end of the branches represents.

Comparing each branch's result to `0` (`.length === 0`, `.size === 0`, `Object.keys(...).length === 0`) turns the count into the boolean the spec actually wants, rather than returning the raw count like `size` does.

The solution

js
/**
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
 */
export default function isEmpty(value) {
  if (value == null) return true;
  if (Array.isArray(value) || typeof value === "string") return value.length === 0;
  if (value instanceof Map || value instanceof Set) return value.size === 0;
  if (typeof value === "object") return Object.keys(value).length === 0;
  return true;
}

Time O(n)Space O(1)

All entries