For the longest time, I have used this method to filter out undefined/null values from arrays in JS.
const filteredArray = arrayToFilter.filter(x => x !== undefined);
I came across a similar situation not too long ago where someone needed to filter undefined objects from an array and used this mysterious syntax to do so..
const filteredArray = arrayToFilter.filter(Boolean);
It works! But why does it work exactly?
Let's break it down piece by piece.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
So for the first example, if x !== undefined, the object becomes part of the new array. If x === undefined, it is left out of the new array.
The filter is using a function that returns true or false. If the result of the function is true, then the value is added to the new array.
What's important to remember here is that undefined is a falsy.
You can use the Boolean() function to find out if an expression (or a variable) is true:
Boolean(10 > 9) // returns true
Instead of passing in an expression, lets see what happens when we only pass in a value.
Boolean(10) // returns true
Why did that return true? Because 10 is a truthy value. It is not false, 0, -0, 0n, "", null, undefined, or NaN.
So, if we pass in a falsy value:
Boolean(undefined) // returns false
Now let's piece it all together.
undefined is a falsy value. Passing a falsy value into the Boolean function would return false. Since the function returns false, the value is not added to the new array. If any other truthy value is passed into the Boolean function, the function returns true, and that value is added to the new array.
So the next time you need to filter out undefined values from an array, save yourself some time and use the Boolean function to do the work for you!