Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
1.3. Is the value empty?
Easy
Topics
This question is in
1. Types, equality and numbersForms, 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
function isEmpty(value) // booleanRequirements
nullandundefinedare empty.- A string is empty only when its length is 0. A string of spaces is not empty.
- 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. - A
Mapor aSetis empty when its size is 0. - 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
undefinedstill counts. - The
argumentsobject and class instances follow rule 5. - Numbers, booleans, symbols, bigints and functions hold no items, so they are empty.
isEmptydoes not change the value.
Examples
isEmpty(null); // true
isEmpty(""); // true
isEmpty(" "); // false
isEmpty([]); // true
isEmpty(new Array(3)); // falseisEmpty(new Map()); // true
isEmpty(new Set([undefined])); // false
isEmpty({}); // true
isEmpty({ a: undefined }); // false
isEmpty(Object.create({ a: 1 })); // true: a is inheritedisEmpty(42); // true
isEmpty(() => 1); // trueEnvironment
- Plain JavaScript in a browser page; the tests call the global
isEmptyfromis-empty.js. WeakMap,WeakSetand typed arrays are not part of the tests.- Any built-in may be used.
Hints
- Which kinds of value keep their items somewhere other than their own properties?
- What does
Object.keysleave 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…