Sub topic 14
Truthy Is Not the Same as == true
Earlier chapters covered truthiness: the rule that decides whether a value counts as true in an if statement, a ternary, or a logical operator. This chapter covers a different rule that looks similar and gets confused with it: loose equality with ==. When you write value == true or value == false, JavaScript does not ask whether the value is truthy. It runs a separate conversion algorithm that works with numbers, and the two rules disagree on many common values.
This chapter assumes you know the falsy values, can use Boolean() and !!, and know that === compares without type conversion. You should also be comfortable reading console.log output.
Two Questions That Sound Alike
These two lines look like they ask the same thing:
const value = [];
if (value) console.log("truthy"); // logs "truthy"
if (value == true) console.log("== true"); // logs nothingThe first line asks: "If I convert value to a boolean, is it true?" An empty array is an object, and every object is truthy, so the answer is yes.
The second line asks: "Is value loosely equal to the boolean true?" Loose equality never converts the array to a boolean. It converts the boolean to a number, then converts the array to a primitive, then compares numbers. The result is false.
So an empty array is truthy, it is not == true, and as you will see below, it is == false.
How == Handles a Boolean Operand
The loose equality algorithm in the ECMAScript specification (IsLooselyEqual) has a rule for booleans: if either operand is a boolean, convert that boolean to a number and start the comparison again. true becomes 1 and false becomes 0.
After that step, x == true is really x == 1 and x == false is really x == 0. The remaining rules then apply:
- If the other operand is an object, convert it to a primitive. For arrays this usually means calling
toString(), so[]becomes""and[0]becomes"0". A plain object becomes"[object Object]". - If one side is a string and the other is a number, convert the string to a number.
""and whitespace-only strings become0. Non-numeric strings becomeNaN. - Compare the numbers.
NaNis never equal to anything.
null and undefined follow their own rule. They are loosely equal only to each other, so null == false and undefined == false are both false, even though both values are falsy.
Both paths end at true, but they answer opposite questions. The left path says "this array is truthy." The right path says "this array equals false."
Walking Through the Surprising Cases
Here is the trace for some values you will meet in real code.
"0" == false: false becomes 0. Now the comparison is "0" == 0. The string "0" becomes the number 0. 0 == 0 is true. But "0" is a non-empty string, so it is truthy.
"2" == true: true becomes 1. "2" becomes 2. 2 == 1 is false. Yet "2" is truthy. The same applies to the number 2: 2 == true is false.
" " == false: a string with only whitespace converts to 0, so this is true. The string is non-empty, so it is truthy.
{} == false: the object becomes "[object Object]", which converts to NaN. NaN == 0 is false. {} == true is also false. The object equals neither boolean.
NaN == false: NaN equals nothing, so this is false, even though NaN is falsy.
The values null, undefined, NaN and {} are each loosely equal to neither boolean. "0", [] and " " are truthy yet loosely equal to false.
A Side-by-Side Table
This script prints the truthiness of each value next to its loose comparisons with true and false. Run it in Node.js or a browser console.
const samples = [
["true", true],
["false", false],
["0", 0],
["1", 1],
["2", 2],
['""', ""],
['"0"', "0"],
['"1"', "1"],
['" "', " "],
["[]", []],
["[0]", [0]],
["[1]", [1]],
["{}", {}],
["null", null],
["undefined", undefined],
["NaN", NaN],
];
const rows = samples.map(([label, v]) => ({
value: label,
truthy: Boolean(v),
"== true": v == true,
"== false": v == false,
}));
console.table(rows);The output matches this table:
| Value | Truthy? | `== true` | `== false` |
|---|---|---|---|
| `true` | true | true | false |
| `false` | false | false | true |
| `0` | false | false | true |
| `1` | true | true | false |
| `2` | true | false | false |
| `""` | false | false | true |
| `"0"` | true | false | true |
| `"1"` | true | true | false |
| `" "` | true | false | true |
| `[]` | true | false | true |
| `[0]` | true | false | true |
| `[1]` | true | true | false |
| `{}` | true | false | false |
| `null` | false | false | false |
| `undefined` | false | false | false |
| `NaN` | false | false | false |
Read down the columns. If == true meant "is truthy," the second and third columns would match. They match for only five of the sixteen rows. The same goes for == false and "is falsy": the two disagree on "0", " ", [], [0], null, undefined and NaN.
Where This Bites in Real Code
The bug usually appears when data arrives as strings, such as form fields, query parameters, environment variables, or CSV cells.
const params = new URLSearchParams("debug=0&verbose=1&count=2");
const debug = params.get("debug"); // "0"
const verbose = params.get("verbose"); // "1"
const count = params.get("count"); // "2"
if (debug) console.log("debug is truthy"); // logs: "0" is a non-empty string
if (debug == false) console.log("debug == false"); // also logs
if (verbose == true) console.log("verbose == true"); // logs
if (count == true) console.log("count == true"); // does not logEach line seems reasonable on its own. Taken together, debug is both truthy and equal to false, and count is truthy but not equal to true. None of these checks says what the developer meant. The fix is to compare against the exact value you expect:
const params = new URLSearchParams("debug=0&verbose=1");
const debugOn = params.get("debug") === "1";
const verboseOn = params.get("verbose") === "1";
console.log(debugOn, verboseOn); // false trueA second common mistake is writing if (flag == true) when flag is supposed to be a boolean. If flag really is a boolean, the comparison adds nothing. If it is not, the comparison gives the confusing answers shown in the table. Either way, if (flag) or if (flag === true) is clearer.
Choosing the Right Check
Pick the check that matches the question you are asking:
| You want to know | Write |
|---|---|
| Is the value truthy? | `if (x)` |
| Is the value falsy? | `if (!x)` |
| Is the value exactly the boolean `true`? | `x === true` |
| Is the value `null` or `undefined`? | `x == null` or `x ?? fallback` |
| Does a string field hold a specific flag? | `x === "1"` or `x === "true"` |
| Is the value a non-empty array? | `Array.isArray(x) && x.length > 0` |
The x == null idiom is the one loose comparison many style guides allow, because its rule is simple: it matches null and undefined and nothing else. Comparing anything with a boolean using == has no such simple rule.
Why the Two Rules Differ
Truthiness uses the specification's ToBoolean operation. ToBoolean is a fixed lookup with no method calls: a short list of falsy primitives, and everything else, including every object, is true. It never calls toString() or valueOf().
Loose equality comes from a different design goal: comparing values of mixed types, mostly numbers and strings. It treats booleans as the numbers 1 and 0, and it does call valueOf() and toString() on objects. You can watch this happen:
const sneaky = {
valueOf() {
console.log("valueOf called");
return 0;
},
};
console.log(Boolean(sneaky)); // true, and valueOf is never called
console.log(sneaky == false); // logs "valueOf called", then trueBoolean(sneaky) never touches the object's methods. sneaky == false runs user code to get a primitive. So a loose comparison with a boolean can even have side effects, which a truthiness check never has.
Exercise
Predict the output of each line, then explain the difference between the first two: console.log(Boolean("false")); console.log("false" == false); console.log([0] == false); console.log(null == false);
Show answer
true, false, true, false. "false" is a non-empty string, so it is truthy. In "false" == false, the boolean becomes 0 and the string "false" becomes NaN, and NaN == 0 is false. For [0] == false, the array becomes "0", which becomes 0, and 0 == 0 is true. null is loosely equal only to null and undefined, so null == false is false even though null is falsy.
Exercise
A config loader reads process.env.CACHE, which is either undefined, "true", or "false". A teammate writes: const cacheEnabled = process.env.CACHE == true; Why is this wrong for every possible input, and what should it be?
Show answer
true converts to 1. "true" and "false" both convert to NaN, and undefined is loosely equal only to null and undefined, so the expression is false in all three cases and caching can never be enabled. Compare against the expected string instead: const cacheEnabled = process.env.CACHE === "true";
Exercise
Find a value that is truthy and also loosely equal to false, and a value that is falsy but loosely equal to neither true nor false. Explain each.
Show answer
"0" works for the first: it is a non-empty string, so it is truthy, and "0" == false becomes "0" == 0, then 0 == 0, which is true. [] and " " also work. NaN works for the second: it is falsy, but NaN is not equal to any value, so NaN == true and NaN == false are both false. null and undefined also work, because they are loosely equal only to each other.