Truthiness & Filter()

One of the fun parts of programming is finding clever ways to do things. There’s always more than one way to peel a potato in software development. When using Array.filter() to test if an element exists or not in an array, one can use a variety of different ways to accomplish the same goal thanks mostly, to “truthiness.”

Truthiness

In a software development context, truthiness is the process with which a value is judged to be either true or false. It changes with different languages but generally anything that is considered to not have a value or be empty is considered false, any the converse is true.

Array.filter()

In Javascript, the Array object has a filter() method which allows you to give a callback function to return elements filtered on some form of test.

Assume we have an array of values:

let list = [ 0, 0, 5, 10, 0, 3, 6, undefined, "" ];

And let’s say you wanted to count the number of non-zero values:

list.filter( c => c > 0 ).length;

// Returns 4

Truthiness allows us to shorten ‘c > 0‘ to simply testing for ‘c’:

list.filter( c => c ).length;

// Returns 4

Another way of doing this is explicitly casting the value as a Boolean and testing if its true:

list.filter( Boolean ).length;

// Returns 4

Conditions

Zero’s are considered false but there might be times where zero is a valid value for your application. If you want to consider them as true values, you would need to add conditions to filter().

list.filter( c => c == 0 || Boolean(c) ).length;

// Returns 7

Conclusion

All of these different methods are effectively the same, and in the compiler are treated the same way. It’s up to you to decide how you want to test for true in your application.