This next bonfire will have us deal with falsy values in JavaScript. We are tasked with creating a function that takes an array, and removes all falsy values from it. Let’s first shear some light on what falsey values actually are.
Most programming languages have what we know as boolean data types, which can be set to true or false. In JavaScript, every value has an inherent boolean value, known as either truthy or falsy. A truthy or falsy value will behave as expected in a logical comparison, but it can cause some problems if not treated with care and understanding.
In JavaScript, the following values are always falsy:
- false
- null
- undefined
- NaN
- 0
- “” (an empty string)
Any other value will always be truthy. That includes empty functions, objects, arrays, or strings containing “0” or “false” for example.
Some falsy values (null, undefined and NaN) behave a little differently. NaN for example, while falsy, is not equivalent to anything (even to itself). The values undefined and null are only equivalent to themselves.
To detect falsy values, we can use the strict equals (===) and strict not equals (!==) signs, which compare objects by value and type. In short, any value that would return false in a logic comparison (without the use of the strict equals or not equals) will turn out to be a falsy value, while everything else is truthy.
Let’s use this knowledge and the filter method to solve our current problem:
function bouncer(array) { return array.filter(function(x) { return x; }); }
The filter method will only return those values that result in a truthy value when evaluated, killing every bird in out bonfire sky with one single -and elegant- stone. The returned array will only contain truthy values.
Watch out for truthy and falsy values when comparing values in JavaScript, and remember to always use the strict equals and strict not equals signs to be on the safe side.