This page looks best with JavaScript enabled

Filter Falsy Values in Array

 ·   ·  ☕ 2 min read

Remember to filter your arrays before doing array-wise operation. Filtering falsy values must be the first operation even if you do not have specific filtering requirements.

Consider this array -

1
const nums = [1, 3, 5, undefined, 7, 9, null];

If you are in control of the data source, you can very well expect to filter only when necessary. But any kind of array operations, or data from external systems can cause all kinds of unexpected results.

We have seen how unexpected values impact array sort before. As you can imagine filtering goes beyond a simple array sort.

Thanks to the loose-typing, Javascript can come back with surprises when least expected. The only defensive programming technique in those cases is to check for data before runtime starts throwing a tantrum.

Filtering arrays is one of those techniques.

If you are well aware of the validations that go in the array element, it may be a good idea to apply some of those simple validations to check data sanctity.

Else, consider a simple true/false check, and apply filter on the array. We have seen this before.

1
2
3
4
const nums = [1, 3, 5, undefined, 7, 9, null];
const numsFiltered = nums.filter(val => !!val);
console.log(numsFiltered);
// [ 1, 3, 5, 7, 9 ]

A simpler way to do that can be -

1
2
3
4
const nums = [1, 3, 5, undefined, 7, 9, null];
const numsFiltered = nums.filter(Boolean);
console.log(numsFiltered);
// [ 1, 3, 5, 7, 9 ]

I personally prefer the more readable format using anon function - it is more explicit. Both ways lead to similar results.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things