Sub topic 1
What Counts as True: Truthy and Falsy Values
Every if, while, and for in JavaScript tests a condition. That condition does not need to be a boolean. You can write if (user) or while (queue.length), and JavaScript will convert whatever value you give it into true or false before deciding what to do. This chapter explains exactly how that conversion works, so you can predict the result for any value instead of guessing.
Prerequisites
This chapter assumes you are comfortable with:
- Basic JavaScript syntax: variables, expressions, and statements
- Declaring variables with
letandconst - Primitive types (number, string, boolean,
null,undefined, bigint), arrays, and plain objects - Writing and calling functions, including arrow functions
You do not need to know if statements in detail yet. They are covered in a later chapter. Here we only use them to show how a value behaves in a condition.
The Working Model: Boolean Conversion
When JavaScript needs a boolean and gets some other value, it applies an internal operation the specification calls ToBoolean. You can call the same conversion yourself with Boolean(value) or with double negation, !!value.
A value is truthy if ToBoolean turns it into true. A value is falsy if ToBoolean turns it into false.
The rule is short. A small, fixed list of values is falsy. Every other value is truthy. You do not need to memorize what is truthy, only the falsy list.
The Complete List of Falsy Values
| Value | Type | Notes |
|---|---|---|
| `false` | boolean | The boolean itself |
| `0` | number | Zero |
| `-0` | number | Negative zero, a separate value in IEEE 754 floating point |
| `0n` | bigint | BigInt zero |
| `""` | string | The empty string (also `''` and `` ` ` `` with nothing inside) |
| `null` | null | Intentional absence of a value |
| `undefined` | undefined | Missing value, unset variable or property |
| `NaN` | number | "Not a Number", the result of failed numeric operations |
That covers it for values you create yourself. Browsers have one historical oddity: document.all is an object, but it is falsy for backward compatibility with very old scripts. You will almost never meet it, but it is the only object that is not truthy.
console.log(Boolean(0), Boolean(""), Boolean(null), Boolean(NaN));
// false false false false
console.log(Boolean([]), Boolean({}), Boolean("0"), Boolean("false"));
// true true true trueThe second line is where most surprises come from. An empty array and an empty object are truthy. The strings "0" and "false" are truthy too, because they are non-empty strings. ToBoolean never looks inside a string to read its meaning. It only checks whether the length is zero.
Truthy Values That Surprise People
Since everything outside the falsy list is truthy, the following all count as true:
const surprises = [
[], // empty array
{}, // empty object
"0", // string containing zero
" ", // string containing a space
"false", // string containing the word false
-1, // any nonzero number, including negatives
Infinity,
-Infinity,
() => {}, // any function
new Date(NaN), // an invalid Date is still an object
new Boolean(false), // a wrapper object, not the primitive false
];
for (const value of surprises) {
console.log(Boolean(value));
}
// prints true eleven timesTwo of these deserve a closer look.
new Boolean(false) creates an object that wraps the primitive false. Objects are always truthy, so the wrapper is truthy even though it represents false. The same applies to new Number(0) and new String(""). Do not use these constructors. Call Boolean(x), Number(x), or String(x) without new to get primitives.
new Date(NaN) produces an "Invalid Date" object. It is still an object, so if (date) will not catch it. Check Number.isNaN(date.getTime()) instead.
Where Truthiness Applies
ToBoolean runs anywhere JavaScript needs a yes-or-no answer:
- The condition of
if,while,do...while, and the middle part offor - The first operand of the conditional operator
a ? b : c - The operand of logical NOT,
!value - Callbacks for
filter,some,every,find, andfindIndex, whose return values are converted to booleans
The && and || operators also test truthiness, but they return one of the original operands, not a boolean. That behavior gets its own chapter. For now, keep in mind that "a" || "b" evaluates to "a", not true.
const words = ["apple", "", "pear", "", "fig"];
const nonEmpty = words.filter((w) => w); // returns the string, then converted
console.log(nonEmpty); // ["apple", "pear", "fig"]
console.log(!"hello", !!"hello"); // false true
console.log(!0, !!0); // true falseCommon Errors and How to Avoid Them
Treating zero as "missing"
The most frequent bug is a check meant to detect a missing value that also rejects a valid 0.
function formatPrice(price) {
if (!price) {
return "Price unavailable";
}
return `$${price.toFixed(2)}`;
}
console.log(formatPrice(19.5)); // "$19.50"
console.log(formatPrice(undefined)); // "Price unavailable"
console.log(formatPrice(0)); // "Price unavailable" <- bug: free itemSay exactly what you mean instead:
function formatPrice(price) {
if (price === undefined || price === null) {
return "Price unavailable";
}
return `$${price.toFixed(2)}`;
}
console.log(formatPrice(0)); // "$0.00"The ?? operator, covered later, makes this pattern shorter.
Treating the empty string as "missing"
The same trap applies to text. A form field the user cleared on purpose contains "", and that may be a valid answer. If you only want to reject absent values, compare against null and undefined explicitly. If you want to reject blank input, including whitespace, be explicit about that too:
function isBlank(text) {
return text === undefined || text === null || text.trim() === "";
}
console.log(isBlank(" ")); // true
console.log(isBlank("hi")); // false
console.log(isBlank("")); // trueChecking an empty array with `if (array)`
Because [] is truthy, if (items) only tells you the array exists. To test for contents, check the length:
const items = [];
if (items) {
console.log("runs even though the array is empty");
}
if (items.length > 0) {
console.log("never runs for an empty array");
}if (items.length) also works, because 0 is falsy. Writing > 0 makes the intent clearer to readers.
Checking an empty object
Empty objects are truthy as well. Count the keys:
const options = {};
console.log(Boolean(options)); // true
console.log(Object.keys(options).length === 0); // true, so it is emptyForgetting that `NaN` is falsy
A failed parse returns NaN, which is falsy. So is a successful parse of "0". A truthiness check cannot tell these apart:
const inputs = ["42", "0", "abc"];
for (const input of inputs) {
const n = Number(input);
console.log(input, Boolean(n), Number.isNaN(n));
}
// "42" true false
// "0" false false
// "abc" false trueUse Number.isNaN(n) to detect a failed conversion.
When Truthiness Checks Are the Right Choice
Truthiness checks are fine, and idiomatic, when every falsy value really means "nothing here":
- Object references that are either an object or
null/undefined, such asif (user)orif (element) - Optional callbacks:
if (onDone) onDone(); - Strings where empty genuinely means absent, such as an optional error message
They are risky whenever 0, "", false, or NaN is a legitimate value in your data. A good habit is to ask "which falsy values can actually reach this line?" If the answer includes a valid one, write an explicit comparison.
Summary
- JavaScript converts any value in a condition to a boolean with ToBoolean.
- Only
false,0,-0,0n,"",null,undefined, andNaNare falsy (plusdocument.allin browsers). - Everything else is truthy, including
[],{},"0","false", and wrapper objects likenew Boolean(false). - Use truthiness for "object or nothing" checks. Use explicit comparisons when
0,"", orfalseare valid data.
Exercise
Predict the output of console.log([0, "", " ", [], null, "0", -0, 0n, {}].map(Boolean)).
Show answer
[false, false, true, true, false, true, false, false, true]. The single space and "0" are non-empty strings, and the empty array and empty object are objects, so all four are truthy. The rest are in the falsy list.
Exercise
A function setVolume(level) starts with if (!level) level = 50; to apply a default when no argument is passed. A user calls setVolume(0) to mute. What happens, and how would you fix it without using ???
Show answer
0 is falsy, so the check replaces it with 50 and the volume goes up instead of muting. Fix it by testing only for a missing value: if (level === undefined) level = 50; (add || level === null if null should also mean "use the default").
Exercise
Why does if (new Boolean(false)) { console.log("yes"); } print "yes", and what should you write instead to get a primitive boolean from a value?
Show answer
new Boolean(false) creates a wrapper object, and all objects are truthy regardless of what they wrap. Use Boolean(value) without new (or !!value), which returns the primitive true or false.