FundamentalsChapter 19 of 21
Truthy and Falsy
The eight falsy values, and why the list is worth memorising.
Every value answers yes or no
Anywhere a condition is expected, JavaScript converts whatever it is given to a boolean. Most values are truthy; the falsy ones are a short list worth learning by heart.
JavaScript
const falsy = [false, 0, -0, 0n, '', null, undefined, NaN];
console.log(falsy.map(Boolean));Output
[false, false, false, false, false, false, false, false]
That is the complete list: false, 0, -0, 0n, the empty string, null, undefined and NaN. Everything else is truthy.
The ones that surprise people
JavaScript
console.log(Boolean('0'));
console.log(Boolean('false'));
console.log(Boolean([]));
console.log(Boolean({}));
console.log(Boolean(-1));Output
true true true true true
An empty array and an empty object are both truthy, because they are objects and every object is truthy. Any non-empty string is truthy, including "0" and "false".
Where it bites
JavaScript
function describe(count) {
if (!count) {
return 'nothing to show';
}
return count + ' items';
}
console.log(describe(5));
console.log(describe(0));Output
5 items nothing to show
Gotcha
Zero is falsy, so a count of exactly 0 takes the same branch as a missing value. When zero is meaningful, test for what you actually mean: count === undefined or count == null.
Checking emptiness
Because [] and {} are truthy, emptiness has to be asked about directly.
JavaScript
const list = [];
const settings = {};
console.log(list.length === 0);
console.log(Object.keys(settings).length === 0);Output
true true
Converting on purpose
Boolean(value) is the clear way to convert. You will also see !!value, which is two negations and does the same thing.
JavaScript
const name = 'Ada';
console.log(Boolean(name), !!name);Output
true true
Test yourself
2 questionsWhich of these is truthy?
Show the answer
[] Every object is truthy, and an empty array is still an object.
Why can if (!count) be a bug?
Show the answer
0 is falsy, so a real count of zero is treated as missing Test for null or undefined explicitly when zero is a legitimate value.
Equality
Why === is the default and == is a chapter about history.