Skip to curriculum
Jump to the editor

1.3. Is the value empty?

Easy
Topics
10–15 min

Forms, API responses and settings all need the same check: is there anything in this value? A search filter with no options set, a cart with no items, a response with no fields. One isEmpty that understands every kind of collection saves a tangle of length, size and Object.keys checks spread through the code.

Write isEmpty(value) in is-empty.js.

Signature

JAVASCRIPT
function isEmpty(value) // boolean

Requirements

  1. null and undefined are empty.
  2. A string is empty only when its length is 0. A string of spaces is not empty.
  3. An array is empty only when its length is 0. A sparse array such as new Array(3) has a length of 3, so it is not empty.
  4. A Map or a Set is empty when its size is 0.
  5. Any other object is empty when it has no own, enumerable, string keys: inherited keys, non-enumerable keys and symbol keys do not count. A key whose value is undefined still counts.
  6. The arguments object and class instances follow rule 5.
  7. Numbers, booleans, symbols, bigints and functions hold no items, so they are empty.
  8. isEmpty does not change the value.

Examples

JAVASCRIPT
isEmpty(null);         // true
isEmpty("");           // true
isEmpty("  ");         // false
isEmpty([]);           // true
isEmpty(new Array(3)); // false
JAVASCRIPT
isEmpty(new Map());              // true
isEmpty(new Set([undefined]));   // false
isEmpty({});                     // true
isEmpty({ a: undefined });       // false
isEmpty(Object.create({ a: 1 })); // true: a is inherited
JAVASCRIPT
isEmpty(42);       // true
isEmpty(() => 1);  // true

Environment

  • Plain JavaScript in a browser page; the tests call the global isEmpty from is-empty.js.
  • WeakMap, WeakSet and typed arrays are not part of the tests.
  • Any built-in may be used.

Hints

  1. Which kinds of value keep their items somewhere other than their own properties?
  2. What does Object.keys leave out?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…