Developer Notes

JavaScript: is something empty?

January 13, 2021

Often the question is is something empty ? And what is empty really? The quick answer is empty is what we decide to be empty. The function below, the standart Array and Object are just tested to see if they have entries or keys. But for example boolean and numbers they are not empty they always have some value, so we decide what value is empty and what not.

So said like that, everything bigger than 0 is not empty, true and false are empty.

The method below don’t handle Set, Map, WeakMap.

1function empty(value) {
2 return (
3 (value === undefined || value === null)
4 || (typeof value === 'number' && value <= 0)
5 || (Array.isArray(value) && value.length === 0)
6 || (typeof value === 'object' && Object.keys(value).length === 0)
7 )
8}

In addation to that we need to add some test to make sure everything will continue to work:

1describe('empty', () => {
2 it('should check value and find is it empty or not', () => {
3 [
4 [true, []],
5 [false, [2]],
6 [true, {}],
7 [false, { foo: 1 }],
8 [true, null],
9 [true, undefined],
10 [false, true],
11 [false, false],
12 [false, 1],
13 [false, 5],
14 [true, 0]
15 ].forEach(([expectedType, value]) => {
16 expect(empty(value)).toBe(expectedType)
17 })
18 })
19})

My name is Bozhidar Dryanovski and I'm a Software Engineer at Clarity
You should follow me on Twitter or Check my work at Github

© 2021, Build version 2.0.5