Truthy and Falsy in Conditions
Any value can sit in a condition, not just a boolean, and knowing which values count as false prevents a whole family of quiet bugs.
Six values are falsy and everything else is truthy, including an empty array and the string zero. Checking a value directly is convenient, and dangerous whenever zero or an empty string is a legitimate answer.
EXERCISE
1A Condition Does Not Need a Boolean
JavaScript converts whatever you put in a condition into true or false, which makes some very short checks possible.
You met the six falsy values as a type conversion. Here is what they do inside an if.
The condition is converted, not compared:
if ("hello") console.log("runs"); // a non-empty string is truthy
if (42) console.log("runs"); // any non-zero number
if ([]) console.log("runs"); // an empty array is an object
if ({}) console.log("runs"); // so is an empty object
if ("") console.log("skipped"); // the six falsy values
if (0) console.log("skipped");
if (null) console.log("skipped");
if (undefined) console.log("skipped");
if (NaN) console.log("skipped");
if (false) console.log("skipped");
Which is why these short checks work:
const user = { name: "Ada" };
// "Does this property exist and hold something?"
if (user.name) {
console.log(`Hello ${user.name}`); // Hello Ada
}
// "Was anything passed in?"
function greet(name) {
if (!name) {
console.log("Hello stranger");
return;
}
console.log(`Hello ${name}`);
}
greet(); // Hello stranger
greet("Ada"); // Hello Ada
And the shape to recognise in real code:
const items = ["a", "b"];
if (items.length) {
console.log(`${items.length} items`); // 2 items
}
// length is 0 when empty, and 0 is falsy.
// This is the correct way to test an array, because [] itself is truthy.
if (list) is almost always a mistake and if (list.length) is almost always what was meant, because an empty array is an object and every object is truthy. This is the most common truthiness bug there is, and it looks completely reasonable until the day it silently does nothing.
EXERCISE
2When a Falsy Value Is a Real Answer
Zero and the empty string are legitimate data in many programs, and a truthiness check cannot tell them apart from missing.
The convenience of if (value) costs you the ability to distinguish empty from absent.
The bug, in the shape it usually arrives:
function describeStock(count) {
if (!count) {
return "Stock level unknown";
}
return `${count} in stock`;
}
console.log(describeStock(5)); // 5 in stock
console.log(describeStock(undefined)); // Stock level unknown correct
console.log(describeStock(0)); // Stock level unknown WRONG
// Zero is a perfectly good reading. It means sold out.
The fix is to say what you actually mean:
function describeStock(count) {
if (count === undefined || count === null) {
return "Stock level unknown";
}
if (count === 0) {
return "Out of stock";
}
return `${count} in stock`;
}
console.log(describeStock(0)); // Out of stock
console.log(describeStock(undefined)); // Stock level unknown
The same trap with text:
const form = { note: "" };
if (!form.note) {
console.log("No note supplied"); // but the user DID supply an empty note
}
// If the difference matters, test for it:
if (form.note === undefined) {
console.log("Field was never filled in");
} else if (form.note === "") {
console.log("Field was cleared deliberately");
}
Pro Tip: Ask one question before writing a truthiness check: can this value legitimately be
0,""orfalse? For a name or a list, no, so the short form is fine. For a count, a price, a score, a search term or a checkbox, yes, and then you must compare explicitly. Getting this wrong produces no error, just wrong behaviour at the worst moment.
EXERCISE
3Writing Conditions That Read Clearly
A condition is read far more often than it is written, and a few habits make the difference between obvious and puzzling.
Do not compare a boolean to true:
const isReady = true;
if (isReady === true) { } // works, but says it twice
if (isReady) { } // say it once
if (isReady === false) { } // works
if (!isReady) { } // clearer
Name a complicated condition instead of inlining it:
const user = { age: 20, isBanned: false, plan: "pro" };
// Hard to read at the point of decision:
if (user.age >= 18 && !user.isBanned && (user.plan === "pro" || user.plan === "team")) {
console.log("Allowed");
}
// Named, and now the if is a sentence:
const isAdult = user.age >= 18;
const isPaid = user.plan === "pro" || user.plan === "team";
const canAccess = isAdult && isPaid && !user.isBanned;
if (canAccess) {
console.log("Allowed");
}
Prefer positive names, because negatives stack badly:
const isNotHidden = true;
if (!isNotHidden) { } // "not not hidden". Stop and think. Every time.
const isVisible = true;
if (!isVisible) { } // reads straight through
And test for the thing, not for its opposite:
// Inverted, so the reader flips it in their head:
if (!(items.length === 0)) {
console.log(`Showing ${items.length} items`);
} else {
console.log("Nothing to show");
}
// Stated directly:
if (items.length === 0) {
console.log("Nothing to show");
} else {
console.log(`Showing ${items.length} items`);
}
Pro Tip: A named condition is free at runtime and worth a great deal at reading time. When you catch yourself counting brackets to work out what an
ifis asking, that is the signal to pull the expression out, give it a name that states the rule in English, and let theifbecome one word.
