JavaScript Quick Tip: Quickly Filter Out All Falsy Values From An Array
How to efficiently make use of first-class functions and the Boolean constructor function
Working with arrays in a functional way has mostly become the default when working with JavaScript these days. Why should you use a traditional imperative loop, like for, for..of, while, do..while, etc., when you can use map, filter, and forEach?
These functional methods have one caveat, though: You can never throw from them without aborting the whole pipeline.
someArray.map((value) => {
if (someConditionMet) {
throw new Error('...'); // this is not the best idea...
}
// ...
return someValidValue;
});
So what do you do then? Well, you can return null to mark that you have an invalid result.
someArray.map((value) => {
if (someConditionMet) {
return null; // now the pipeline can continue
}
// ...
return someValidValue;
});
That's fine. If you don't want your pipeline to abort, you can continue using null values as a marker for "this didn't work out".
But what if you want to get rid of those values afterward? Perhaps something like this?
someArray.map((value) => {
if (someConditionMet) {
return null; // now the pipeline can continue
}
// ...
return someValidValue;
}).filter((value) => value);
This leaves you only with valid values, which is perfectly fine, but we can make this even shorter.
The Code
JavaScript has first-class functions. You can pass any function reference to any other function that expects a function as this particular argument. And the Boolean constructor is actually the function responsible to define truthy and falsy.
const array = [1, null, undefined, 0, 2, "", 4];
const result = array.filter(Boolean);
When the filter step of this pipeline has run, you only have all truth values left, and can continue working with them without having to handle special cases like null or undefined.
The Whole Tip As An Image
If you like visual content more, or if you want to store it for later, I put all this into one image for you. I hope you like it!
Before You Leave
If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.
I'd love to count you as my ever-growing group of awesome friends!