The truth(y) of the matter
Earlier this evening, I was explaining some code I wrote and several times over found myself referencing the idea of a truthy value. Met with a few questions, I thought this could be a great opportunity to explain.
While this article will not be an exhaustive explanation of all possible outcomes, I hope to show a strong use case for truthy/falsey values.
Let’s write some JavaScript!
const x = 0;
if (x == true) { console.log(`x == true`);} else if (x == false) { console.log(`x == false`);} else if (x === false) { console.log(`x === false`);}//Output: x == false
Now there are a few interesting things happening here. If we run this code, we will find that the number zero equals false, but does not strictly equal false.
There is certainly room for a conversation about the difference between equal and strictly equal, but the point here is that number zero will evaluate to false. Let’s refactor this code.
const x = 0;
if (x) { console.log(`x == true`);} else if (!x) { console.log(`x == false`);}//Output: x == false
Above, we have simplified the conditional statements. If the code within the parenthesis evaluates to truthy, not necessarily true, then the code within the curly brackets will run.
Further documentation of falsy values is available here, and the corresponding documentation of truthy values can be found here.
Let’s now take a look at a more involved example.
const valuesToAssess = [true, Infinity, 1.73, "true", "", []];let numTruthyValues = 0;const falseValueWarning = () => { console.log(`A falsy value has been discovered.`);};valuesToAssess.forEach((value) => { value ? numTruthyValues++ : falseValueWarning();});console.log(`${numTruthyValues} truthy values have been discovered.`);/* Output:
A falsy value has been discovered within the array.
5 truthy values have been discovered.
*/
In the above example, we use a forEach loop to iterate over the array. At each value along the array, we call a conditional (ternary) operator to determine if the value is truthy or falsy. This is a great way to identify potentially bad values such as null, NaN, or undefined. In this case we have found an empty string.
I hope the article has shed a little light on an interesting concept!