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
expect(isEmpty(null)).toBe(true);
expect(isEmpty(undefined)).toBe(true);
expect(isEmpty("")).toBe(true);
expect(isEmpty([])).toBe(true);
expect(isEmpty(" ")).toBe(false);
expect(isEmpty([0])).toBe(false);
expect(isEmpty([undefined])).toBe(false);
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);
expect(isEmpty({})).toBe(true);
expect(isEmpty(Object.create(null))).toBe(true);
expect(isEmpty({ a: 1 })).toBe(false);
expect(isEmpty({ a: undefined })).toBe(false);
expect(isEmpty(Object.create({ a: 1 }))).toBe(true);
expect(isEmpty(Object.defineProperty({}, "hidden", { value: 1, enumerable: false }))).toBe(true);
class Empty {
method() {}
}
class Point {
constructor() {
this.x = 1;
}
}
expect(isEmpty(new Empty())).toBe(true);
expect(isEmpty(new Point())).toBe(false);
for (const value of [0, NaN, 42, false, true, Symbol("s"), 0n]) {
expect(isEmpty(value)).toBe(false);
}
expect(isEmpty(() => {})).toBe(false);
expect(isEmpty(function named() {})).toBe(false);
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).
I'm here to help with isEmpty. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.