Tue, Jan 25, 2022
When using truthy/falsy evaluations in JavaScript extra care must be taken.
Take the following example. The function's intention is to print a message based on how many cars a user has. If no parameter is passed in, it means that the number of cars is not known.
function printNumCarMsg(numCars) {
console.log(
numCars ? `I have ${numCars} car(s).` : "I don't know how many cars I have."
);
}
Testing the function with 2
given as numCars
and without any parameters produces the following. So far so good.
printNumCarMsg(2);
// I have 2 car(s).
printNumCarMsg();
// I don't know how many cars I have.
Now, what if a user does not have any cars? Passing in 0
has the following result. What happened? We do know how many cars there are - 0. So why is this the result?
printNumCarMsg(0);
// I don't know how many cars I have.
Look at the expression numCars ? `I have ${numCars} car(s).` : "I don't know how many cars I have."
. The left side of this expression is a truthy expression. Meaning, 0
would evaluate to false
. The function needs to be modified like so:
function printNumCarMsg(numCars) {
console.log(
typeof numCars !== 'undefined'
? `I have ${numCars} car(s).`
: "I don't know how many cars I have."
);
}
Now we're in business.
printNumCarMsg(0);
// I have 0 car(s).
The lesson here is to be careful when using truthy/falsy values. This isn't limited to expressions, of course. It can happen anywhere you evaluate the value, like if statements.