Basic · 5 of 12 · 14 min read
if, truthy and falsy
The eight falsy values, why an empty array is not one of them, and the operators that let you stop writing if at all.
- Control flow
An if converts whatever you give it to a boolean. It does not ask whether the value is true — it
asks whether the value is truthy, and those are different questions.
The eight falsy values
Memorise this list and you never have to guess again.
| Value | Why |
|---|---|
false |
the boolean itself |
0 |
zero |
-0 |
negative zero, a distinct value that is also falsy |
0n |
the bigint zero |
'' |
the empty string |
null |
|
undefined |
|
NaN |
const falsy = [false, 0, -0, 0n, '', null, undefined, NaN];
console.log(falsy.filter(Boolean)); // [] — not one of them survives
// And the ones that catch people out, all truthy:
console.log(Boolean([])); // true — an empty array is an object
console.log(Boolean({})); // true — so is an empty object
console.log(Boolean('false')); // true — a non-empty string
console.log(Boolean('0')); // true
console.log(Boolean(' ')); // true — a space is a character
console.log(Boolean(-1)); // true — only zero is falsy
console.log(Boolean(Infinity)); // true
console.log(Boolean(() => {})); // true — functions are objects
The array case is the one that produces real bugs:
const items = [];
if (items) console.log('this runs'); // it is an object, so it is truthy
if (items.length) console.log('this does not'); // 0 is falsy — check the length
Checking emptiness properly
“Is there anything here?” is a different question for every type, and if (value) only answers it
correctly for strings and numbers by accident.
const isEmptyString = (s) => s.trim() === '';
const isEmptyArray = (a) => a.length === 0;
const isEmptyObject = (o) => Object.keys(o).length === 0;
const isNullish = (v) => v == null; // null or undefined
console.log(isEmptyString(' '), isEmptyArray([]), isEmptyObject({}), isNullish(undefined));
// true true true true
if, else if, and the ternary
function grade(score) {
if (score >= 90) return 'A';
else if (score >= 80) return 'B';
else return 'C';
}
// With early returns the `else` is noise:
function gradeBetter(score) {
if (score >= 90) return 'A';
if (score >= 80) return 'B';
return 'C';
}
console.log(grade(85), gradeBetter(85)); // B B
A ternary is an expression, so it produces a value — which is what makes it right for assignment and wrong for running two branches of logic:
const score = 85;
const label = score >= 80 ? 'pass' : 'fail';
console.log(label); // "pass"
// Nested ternaries stop being readable fast. This is the limit:
const size = score > 90 ? 'high' : score > 70 ? 'mid' : 'low';
console.log(size); // "mid"
The operators that replace an if
&& and || short-circuit
The right-hand side is never evaluated when the left side already decides the answer:
const expensive = () => {
console.log('ran');
return true;
};
false && expensive(); // nothing logged — `false &&` is already false
true || expensive(); // nothing logged — `true ||` is already true
true && expensive(); // "ran"
And they return an operand, not a boolean, which is what makes them useful for defaults:
console.log(0 || 'fallback'); // "fallback"
console.log('' || 'fallback'); // "fallback"
console.log('value' || 'fallback'); // "value"
console.log(null && 'never'); // null ← the operand, not false
console.log(1 && 2); // 2 ← the last one
?? for “missing”, not “falsy”
|| falls back on all eight falsy values. ?? falls back only on null and undefined — which is
what you almost always meant:
const show = (v) => console.log(v || 'fallback', '|', v ?? 'fallback');
show(0); // fallback | 0 ← `||` threw away a real zero
show(''); // fallback | ← and a real empty string
show(null); // fallback | fallback
show(undefined); // fallback | fallback
show('value'); // value | value
The classic bug this fixes:
function render({ count }) {
const n = count || 10; // a legitimate 0 silently becomes 10
const m = count ?? 10; // 0 stays 0
return [n, m];
}
console.log(render({ count: 0 })); // [10, 0]
?. for “might not be there”
Optional chaining short-circuits the whole expression to undefined as soon as a link is nullish,
instead of throwing:
const user = { name: 'Ana' };
// console.log(user.address.city); // TypeError: Cannot read properties of undefined
console.log(user?.address?.city); // undefined
console.log(user.save?.()); // undefined — the method does not exist, no throw
console.log(user.tags?.[0]); // undefined — works on indexes too
?. and && are not interchangeable, and the difference is the falsy list again:
const count = 0;
console.log(count && count.toFixed(1)); // 0 ← `&&` bailed on a falsy-but-present value
console.log(count?.toFixed(1)); // "0.0" ← `?.` only bails on null/undefined
switch compares with ===
A switch is an if/else if chain with two differences worth knowing: it matches strictly, and a
case falls through to the next one unless you stop it.
function f(n) {
switch (n) {
case 1:
console.log('one');
// no break — execution continues into case 2
case 2:
console.log('two');
break;
default:
console.log('other');
}
}
f(1); // "one" then "two" ← the fall-through
f(2); // "two"
f(9); // "other"
// Strict matching, so a string does not match a number:
switch ('1') {
case 1:
console.log('number one');
break;
default:
console.log('no match'); // this one
}
Deliberate fall-through is the one good use — grouping labels that share a branch:
function size(n) {
switch (n) {
case 1:
case 2:
return 'small'; // both labels share this
default:
return 'large';
}
}
console.log(size(1), size(2), size(9)); // small small large
Common mistakes
if (value) when 0 or '' is valid
Mistake. if (options.retries) use(options.retries).
Why it fails. 0 retries is a real configuration and it is falsy, so the branch is skipped.
What to do instead. Be explicit about what you are testing: if (options.retries != null), or
supply the default with ??.
Forgetting the break
Mistake. A switch where one case does its work and the next one runs too.
Why it fails. A matching case is an entry point, not a block — execution continues downwards
until break, return or the end.
What to do instead. return from each case where you can; it makes the fall-through impossible.
Treating && as a null guard
Mistake. user && user.profile && user.profile.name.
Why it fails. It works, but it also bails on 0, '' and false, and it gets long.
What to do instead. user?.profile?.name — shorter, and it only short-circuits on the two values
that mean “not there”.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
Which of these values is **truthy**?
A switch case does not automatically stop at the end of its block.
Calling f(1) logs both "one" and "two". Why?
function f(n) {
switch (n) {
case 1:
console.log("one");
case 2:
console.log("two");
break;
}
}
f(1);Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.