Sub topic 3
Everything Else Is Truthy, Including Some Surprises
This chapter assumes you can declare variables with let and const, know JavaScript's primitive types and objects, and can read if statements, ternaries and console.log output. You should also know the short list of falsy values from the previous chapter: false, 0, -0, 0n, "", null, undefined and NaN.
The rule for truthy values is simple to state. A truthy value is any value that is not on the falsy list. No second list exists, and no value sits between truthy and falsy. When JavaScript needs a boolean, it checks whether the value is one of those eight falsy values. If it isn't, the value counts as true.
The surprises come from values that look empty, false or zero to a human but are not on the list.
The Working Model: Primitives Are Checked, Objects Always Pass
It helps to split values into two groups.
- Primitives (strings, numbers, bigints, booleans, symbols,
null,undefined) are truthy unless they match one specific falsy value. - Objects, which include arrays, functions, dates, maps, sets, regular expressions and wrapper objects, are always truthy. JavaScript never looks inside an object to decide its truthiness. It doesn't check length, size, contents or what
valueOf()returns.
The one exception to "objects are always truthy" is document.all, a legacy browser object covered in the final chapter. Treat it as a historical oddity. Everything you write yourself follows the rule.
Surprising Truthy Primitives
Strings cause most of the confusion. Only the empty string "" is falsy. Every other string is truthy, including strings whose text spells out a falsy value.
const check = (value) => (value ? "truthy" : "falsy");
const primitives = [
["\"0\"", "0"],
["\"false\"", "false"],
["\" \" (one space)", " "],
["\"NaN\"", "NaN"],
["\"null\"", "null"],
["\"undefined\"", "undefined"],
["-1", -1],
["0.0000001", 0.0000001],
["Infinity", Infinity],
["-Infinity", -Infinity],
["1n", 1n],
["-1n", -1n],
["Symbol()", Symbol()],
];
for (const [label, value] of primitives) {
console.log(label.padEnd(18), check(value));
}
// Every line prints "truthy"A few points to remember:
- Negative numbers are truthy. Only zero (
0and-0) andNaNare falsy numbers.-1is truthy, which matters when you test the result ofindexOf(see the common errors below). - Tiny numbers are truthy.
0.0000001is not zero, so it passes. Floating-point results such as0.1 + 0.2 - 0.3give5.551115123125783e-17, which is truthy even though you might expect zero. - Whitespace strings are truthy.
" ","\n"and"\t"all have a length greater than zero. - Every symbol is truthy, even
Symbol()with no description.
Surprising Truthy Objects
Objects are always truthy, so "empty" containers pass every truthiness check.
const check = (value) => (value ? "truthy" : "falsy");
const objects = [
["[]", []],
["[0]", [0]],
["[[]]", [[]]],
["{}", {}],
["function () {}", function () {}],
["new Map()", new Map()],
["new Set()", new Set()],
["new Date(\"oops\")", new Date("oops")],
["/(?:)/", /(?:)/],
];
for (const [label, value] of objects) {
console.log(label.padEnd(18), check(value));
}
// Every line prints "truthy"Even an invalid date is truthy. new Date("oops") creates a Date object whose internal time value is NaN. Its time value is falsy, but the date itself is an object, so it is truthy. To check whether a date is valid, test the number: Number.isNaN(date.getTime()).
The Wrapper Object Trap
JavaScript has constructor functions for primitives: Boolean, Number and String. Calling them with new creates an object that wraps a primitive. That object is truthy no matter what it wraps.
const flag = new Boolean(false);
const zero = new Number(0);
const empty = new String("");
console.log(typeof flag); // "object"
console.log(flag.valueOf()); // false
if (flag) console.log("new Boolean(false) is truthy"); // logs
if (zero) console.log("new Number(0) is truthy"); // logs
if (empty) console.log("new String(\"\") is truthy"); // logs
const plain = Boolean(false); // no "new": returns a primitive
console.log(typeof plain); // "boolean"
if (!plain) console.log("Boolean(false) is falsy"); // logsYou almost never need new Boolean, new Number or new String. Linters such as ESLint flag them with the no-new-wrappers rule. If you see one in old code, it's a likely source of bugs in any condition that uses it.
The Opposite Surprise: typeof null
The reverse case also catches people. typeof null returns "object" because of a bug that has been in the language since its first version. So null looks like an object to typeof, yet it is falsy.
const value = null;
console.log(typeof value === "object"); // true
console.log(value ? "truthy" : "falsy"); // "falsy"
// Safe object check: rule out null explicitly
const isObject = (v) => typeof v === "object" && v !== null;
console.log(isObject(null)); // false
console.log(isObject({})); // trueA typeof check on its own does not tell you a value is truthy or safe to read properties from.
Summary Table
| Looks empty or false | Actual value type | Truthy? | What to test instead |
|---|---|---|---|
| `"0"` | string | yes | `Number(s) === 0` |
| `"false"` | string | yes | `s === "true"` |
| `" "` | string | yes | `s.trim() !== ""` |
| `[]` | object | yes | `arr.length > 0` |
| `{}` | object | yes | `Object.keys(obj).length > 0` |
| `new Map()`, `new Set()` | object | yes | `m.size > 0` |
| `new Date("oops")` | object | yes | `!Number.isNaN(d.getTime())` |
| `new Boolean(false)` | object | yes | Avoid creating it; use `b.valueOf()` |
| `-1` | number | yes | Compare explicitly, e.g. `i !== -1` |
Where These Surprises Show Up in Real Code
Strings from the outside world
Form fields, URL query strings, environment variables and localStorage all give you strings. A setting that a human reads as "off" arrives as the text "false" or "0", and both are truthy.
const params = new URLSearchParams("debug=false&page=0&name=%20");
const debug = params.get("debug"); // "false"
const page = params.get("page"); // "0"
const name = params.get("name"); // " "
if (debug) console.log("Bug: debug mode is on"); // logs
if (page) console.log("Bug: page looks set"); // logs
if (name) console.log("Bug: name looks filled in"); // logs
// Correct checks
const debugOn = debug === "true";
const pageNumber = Number(page);
const hasName = name !== null && name.trim() !== "";
console.log(debugOn, pageNumber, hasName); // false 0 falseTurn external strings into the type you actually want before you test them. Compare against "true", parse with Number(), or trim the string.
Empty collections
if (results) is true for an empty array, so code that expects "show a 'no results' message when nothing came back" never shows it.
function describe(results) {
if (results.length === 0) return "No results";
return `${results.length} results`;
}
console.log(describe([])); // "No results"
console.log(describe(["a", "b"])); // "2 results"If results might also be null or undefined, handle that case first. Later chapters cover optional chaining and ??, which make that pattern shorter.
Common Errors
- Testing
indexOfby truthiness.if (str.indexOf("x"))is wrong both ways. A match at position0is falsy, and "not found" (-1) is truthy. Usestr.includes("x")orstr.indexOf("x") !== -1. - Treating
[]or{}as "nothing". Check.length,.sizeorObject.keys(...).length. - Trusting string flags.
"false"and"0"are truthy. Compare or parse them. - Using wrapper constructors with
new. The resulting objects are always truthy. - Assuming
typeof x === "object"means usable. It is also true fornull.
Exercises
Exercise
Which of these values are truthy: "0", 0, [], "", " ", new Number(0), -0, -1, {}, NaN, "NaN"?
Show answer
Truthy: "0", [], " ", new Number(0), -1, {}, "NaN". Falsy: 0, "", -0, NaN. Strings are falsy only when empty, objects (including the wrapper new Number(0)) are always truthy, and -1 is a non-zero number.
Exercise
This function should return "empty" for an empty array, but it returns "has items" for []. Explain why and fix it. function status(list) { return list ? "has items" : "empty"; }
Show answer
An array is an object, and objects are always truthy, so [] passes the condition. Test its length instead: return list.length > 0 ? "has items" : "empty";
Exercise
An environment variable FEATUREX is set to the string "0" to disable a feature. The code reads `if (process.env.FEATUREX) enableFeature();`. What happens, and what is a correct check?
Show answer
"0" is a non-empty string, so it is truthy and the feature is enabled anyway. A correct check parses or compares the string explicitly, for example if (process.env.FEATURE_X === "1") enableFeature(); or if (Number(process.env.FEATURE_X) > 0) enableFeature();.
Exercise
Why does if (new Date("not a date")) run its body, and how do you test whether a date is valid?
Show answer
new Date(...) always returns a Date object, and objects are truthy even when their internal time value is NaN. Check validity with !Number.isNaN(date.getTime()).