Skip to the code
cf.

isEmpty

Write isEmpty(value). It returns true when value holds nothing and false otherwise, and it works for every kind of value.

null and undefined are empty. A string or an array is empty when its length is 0, and a Map or a Set when its size is 0.

Any other object, plain or a class instance, is empty when it has no own enumerable string keys: the ones Object.keys lists. Inherited and non-enumerable properties don't count, so Object.create({ a: 1 }) is empty.

Numbers (including 0 and NaN), booleans, symbols, bigints, and functions are never empty: they're values, not containers.

isEmpty(null);             // true
isEmpty("");               // true
isEmpty(new Map());        // true
isEmpty({});               // true
isEmpty({ a: undefined }); // false
isEmpty(new Set([0]));     // false
isEmpty(0);                // false
isEmpty(() => {});         // false

What the tests check

  1. null and undefined are empty
    expect(isEmpty(null)).toBe(true);
    expect(isEmpty(undefined)).toBe(true);
    
  2. strings and arrays are empty only when their length is 0
    expect(isEmpty("")).toBe(true);
    expect(isEmpty([])).toBe(true);
    expect(isEmpty(" ")).toBe(false);
    expect(isEmpty([0])).toBe(false);
    expect(isEmpty([undefined])).toBe(false);
    
  3. Maps and Sets are empty only when their size is 0
    expect(isEmpty(new Map())).toBe(true);
    expect(isEmpty(new Set())).toBe(true);
    expect(isEmpty(new Map([["a", 1]]))).toBe(false);
    expect(isEmpty(new Set([0]))).toBe(false);
    
  4. objects are empty when they have no own enumerable keys
    expect(isEmpty({})).toBe(true);
    expect(isEmpty(Object.create(null))).toBe(true);
    expect(isEmpty({ a: 1 })).toBe(false);
    expect(isEmpty({ a: undefined })).toBe(false);
    
  5. inherited and non-enumerable properties don't count
    expect(isEmpty(Object.create({ a: 1 }))).toBe(true);
    expect(isEmpty(Object.defineProperty({}, "hidden", { value: 1, enumerable: false }))).toBe(true);
    
  6. class instances follow the object rule
    class Empty {
      method() {}
    }
    class Point {
      constructor() {
        this.x = 1;
      }
    }
    expect(isEmpty(new Empty())).toBe(true);
    expect(isEmpty(new Point())).toBe(false);
    
  7. numbers, booleans, symbols, and bigints are never empty
    for (const value of [0, NaN, 42, false, true, Symbol("s"), 0n]) {
      expect(isEmpty(value)).toBe(false);
    }
    
  8. functions are never empty
    expect(isEmpty(() => {})).toBe(false);
    expect(isEmpty(function named() {})).toBe(false);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).