Remove falsy values from an array in JavaScript
Beginner · 3 min read
Lists built from real data often have gaps in them: a missing phone number, a field that came back as null, an empty string from a blank form box. Before you show or count the items, you usually want to drop the empty ones. There is a famous one-liner for this, filter(Boolean), and it is worth knowing both why it works and when it removes too much.
In this tutorial you will clean a mixed list with filter(Boolean), test it against values that look empty but aren't, and write a more careful version that keeps real values like 0. You should know arrays, filter and arrow functions.
Truthy and falsy
When JavaScript needs a yes-or-no answer, in an if for example, it treats every value as either truthy or falsy. There are only eight falsy values:
false, 0, -0, 0n, '' (the empty string), null, undefined and NaN.
Everything else is truthy. That includes some values that look empty: the string '0', the string 'false', an empty array [] and an empty object {}.
Boolean(value) tells you which group a value is in:
console.log(Boolean(0)); // false
console.log(Boolean('0')); // true
console.log(Boolean([])); // true
How filter uses your function
filter(fn) calls fn on each item and keeps the items where fn returns something truthy. It returns a new array and leaves the original alone.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
14 Drop the empty values
easyRemove the falsy values from a mixed list with filter(Boolean). Then decide whether that is really what you wanted, using 0 and '' as your test cases.
Stuck? Three hints, smallest first
- 1.
filter(Boolean)works becauseBooleanis a one-argument function that returns a boolean. - 2. The falsy values are
false,0,-0,0n,‘’,null,undefinedandNaN. Nothing else. - 3. To remove only the absent ones, test
v != null, which is loose on purpose.
Step 1: filter(Boolean)
Boolean is a function that takes one value and returns true or false. That is exactly the shape filter wants, so you can pass it in directly.
const mixed = [0, 1, '', null, 'a', undefined, NaN, 2, false];
const truthy = mixed.filter(Boolean);
console.log(truthy); // [ 1, 'a', 2 ]
console.log(mixed.length); // 9
filter(Boolean) is the same as filter((v) => Boolean(v)), just shorter. Every falsy value has gone, and mixed still has all nine items.
Step 2: things that look empty but stay
console.log(['0'].filter(Boolean)); // [ '0' ]
console.log(['false'].filter(Boolean)); // [ 'false' ]
console.log([[]].filter(Boolean).length); // 1
console.log([{}].filter(Boolean).length); // 1
'0' and 'false' are non-empty strings, so they are truthy. [] and {} are objects, and every object is truthy, however empty it is. So if (list) doesn't tell you whether a list has anything in it. if (list.length) does.
Step 3: did we remove too much?
Look back at Step 1. The 0 was removed. If this list were prices, a free item costing 0 is real data. The same goes for an empty string that means "no middle name".
const prices = [0, 1500, null, 800];
console.log(prices.filter(Boolean)); // [ 1500, 800 ]
The free item has vanished. What we usually mean by "empty" is missing: null or undefined.
Step 4: drop only the missing values
Here is the careful version:
const mixed = [0, 1, '', null, 'a', undefined, NaN, 2, false];
const present = mixed.filter((v) => v != null);
console.log(present); // [ 0, 1, '', 'a', NaN, 2, false ]
console.log(present.length); // 7
Notice it is !=, with one =, not !==. Normally you should use the strict !==, but this is the one place where the loose version is useful. With loose comparison, null and undefined count as equal to each other and to nothing else. So v != null is false for both of them and true for everything else, including 0, '', false and NaN.
console.log(undefined != null); // false
console.log(0 != null); // true
console.log([null, undefined].filter((v) => v != null)); // []
One comparison removes both kinds of missing value.
Step 5: choose on purpose
You now have two tools:
const mixed = [0, 1, '', null, 'a', undefined, NaN, 2, false];
console.log(mixed.filter(Boolean).length); // 3
console.log(mixed.filter((v) => v != null).length); // 7
Use filter(Boolean) when every falsy value really is junk, for example a list of CSS class names where '' and false come from conditions like isActive && 'active'. Use v != null when 0, '' or false could be real answers.
The full solution
The panel runs both filters on the same mixed list and then tries filter(Boolean) on values that only look empty. Press Run to compare what each one keeps.
const mixed = [0, 1, '', null, 'a', undefined, NaN, 2, false];
const truthy = mixed.filter(Boolean);
const present = mixed.filter((v) => v != null); // loose !=, so null AND undefined
console.log('input :', mixed);
console.log('truthy :', truthy);
console.log('present :', present, '<- keeps 0, "" and NaN');
console.log('--- things that look empty but are truthy ---');
console.log("['0'] ->", ['0'].filter(Boolean), 'a non-empty string');
console.log('[[]] ->', [[]].filter(Boolean), 'an empty array is an object');
console.log("['false'] ->", ['false'].filter(Boolean), 'text, not a boolean');
console.log('[{}] ->', [{}].filter(Boolean).length, 'an empty object too');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('filter(Boolean) keeps only the truthy values', truthy, [1, 'a', 2]);
test('0 counts as falsy, so it goes', truthy.includes(0), false);
test('but the string "0" is truthy', ['0'].filter(Boolean), ['0']);
test('an empty array is truthy, being an object', [[]].filter(Boolean).length, 1);
test('and so is the text "false"', ['false'].filter(Boolean), ['false']);
test('filter never mutates its input', mixed.length, 9);
test('v != null keeps the falsy-but-real values', present.length, 7);
test('including the zero', present[0], 0);
test('a single = would have been an assignment, and != null catches both', [null, undefined].filter((v) => v != null), []);
filter(Boolean) is idiomatic and slightly too eager. It removes 0 and '', which are usually real data — a price of zero, a blank middle name. When you mean "drop the missing ones", say v != null: the loose != is deliberate there, because null != null is false and undefined != null is also false, so one comparison covers both.
The truthiness of [] and {} catches people out regularly. Every object is truthy, however empty. if (arr) therefore tells you nothing about whether an array has contents; if (arr.length) does.
Common mistakes
- Using
filter(Boolean)on numbers. It removes0. Usev != nullif zero is a real value. - Writing
v !== null. The strict version keepsundefined. Writev != nullon purpose, orv !== null && v !== undefinedif your team prefers that spelled out. - Testing
if (arr)to see if an array has items. An empty array is truthy. Testarr.lengthinstead.
Try it yourself
- Build a class name from
['btn', isActive && 'active', isBig && 'big']withfilter(Boolean).join(' '), for each mix oftrueandfalse. - From
[3, null, 0, undefined, 7], keep the numbers and add them up. - Write
compact(xs)that removesnull,undefinedandNaN, but keeps0and''.