Notes Tutorials

Conditions and boolean logic

True, false, and everything in between: truthy and falsy values, short-circuit evaluation, == vs ===, || vs ??, De Morgan's laws, and how to keep if statements readable.

7 min readAlso available in Bahasa Indonesia →

In part 0 we saw that every program is built from three control structures: sequence, selection, and iteration. This part is about selection: making a decision. On the surface that’s just if, but underneath are a few rules about what counts as “true” that cause a surprising number of bugs, especially when you switch between languages. It builds on the data types from part 2, because what counts as “true” depends on the type.

Boolean logic in one page

The idea that logic can be calculated like algebra goes back to George Boole, best known for The Laws of Thought (1854). He is “the namesake of the branch of algebra known as Boolean algebra”, which today “forms the foundation of digital circuit design and modern computer science.”

You only need three operations:

A B A and B A or B not A
true true true true false
true false false true false
false true false true true
false false false false true
  • and is true only when both sides are true.
  • or is true when at least one side is true.
  • not flips the value.

De Morgan’s laws: flipping a condition safely

When you need the opposite of a condition, it’s easy to flip it wrongly. De Morgan’s laws tell you how:

  • “The negation of “A and B” is the same as “not A or not B”.”
  • “The negation of “A or B” is the same as “not A and not B”.”

Python can check the first one for every combination:

A     B     not(A and B)  (not A) or (not B)
True   True   False         False
True   False  True          True
False  True   True          True
False  False  True          True

In practice: the opposite of “logged in and verified” is “not logged in or not verified”, not “not logged in and not verified”. Getting the and/or swap wrong here is a classic way to let the wrong people through a check.

Truthy and falsy: what counts as true?

Many languages let you use any value as a condition, not just true or false.

In Python, “Any object can be tested for truth value, for use in an if or while condition”. The documentation lists the values considered false: “None and False”, “zero of any numeric type”, and “empty sequences and collections” such as '', [], and {}. Everything else is true:

>>> for v in [0, 1, '', 'hi', [], [0], None, 0.0]:
...     print(repr(v), bool(v))
0 False
1 True
'' False
'hi' True
[] False
[0] True
None False
0.0 False

JavaScript has a similar idea. MDN defines a falsy value as “a value that is considered false when encountered in a Boolean context.” The falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. But notice what is not on that list:

console.log(Boolean([]), Boolean({}), Boolean("0"));
// true true true

An empty array is falsy in Python but truthy in JavaScript. If you work in both, that difference will catch you at least once.

PHP sides with Python on empty arrays, and adds one surprise of its own. The manual’s list of values that are “considered false” includes “the empty string “”, and the string “0”“:

foreach ([0, "0", "", "0.0", [], [0], null, "false"] as $v) {
    echo str_pad(json_encode($v), 8), var_export((bool) $v, true), "\n";
}
0       false
"0"     false
""      false
"0.0"   true
[]      false
[0]     true
null    false
"false" true

A form field where the user typed 0 arrives as the string "0", and if ($input) treats it as empty.

Go takes the strict route: a condition must be a real boolean. This doesn’t compile:

count := 1
if count { }
./main.go:5:5: non-boolean condition in if statement

More typing, but no surprises: you have to write if count > 0 and say what you mean.

Short-circuit evaluation

and and or stop as soon as they know the answer. The Python docs say or “only evaluates the second argument if the first one is false”, and and “only evaluates the second argument if the first one is true.” That’s why this is safe:

if user is not None and user.is_active:
    ...

If user is None, the second half never runs, so there’s no error from reading .is_active on nothing.

There’s a second detail that’s easy to miss: in Python (and JavaScript), “the Boolean operations or and and always return one of their operands”, not necessarily True or False:

>>> 0 or 5, '' or 'default', 3 and 4, None and 'x'
(5, 'default', 4, None)

That’s why name or "Anonymous" is a common way to provide a default. And it’s also where a subtle bug lives.

The default-value trap: || vs ??

Suppose a quantity can legitimately be 0:

>>> quantity = 0
>>> quantity or 1
1

Oops. 0 is falsy, so the “default” replaced a real value. The same thing happens in JavaScript with ||. That’s why JavaScript added the nullish coalescing operator ??, which “returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.” In contrast, || returns the right side “if the left operand is any falsy value, not only null or undefined.”

console.log(0 || 10, 0 ?? 10);       // 10 0
console.log(JSON.stringify(["" || "x", "" ?? "x"])); // ["x",""]
console.log(null ?? "x");            // x

In Python, write what you mean: 1 if quantity is None else quantity.

PHP has both flavors. The short ternary ?: falls back on any falsy value, like ||. The null coalescing operator “evaluates to expr2 if expr1 is null, and expr1 otherwise”, like JavaScript’s ??:

$quantity = 0;
var_dump($quantity ?: 1);   // int(1)  ← replaced a valid 0
var_dump($quantity ?? 1);   // int(0)

Equality: == vs ===

JavaScript’s == tries to be helpful. MDN: “it attempts to convert and compare operands that are of different types.” The results are often not what anyone wants:

console.log("" == 0, "0" == 0, null == undefined, [] == false);
// true true true true
console.log("" === 0, "0" === 0, null === undefined);
// false false false

The strict operator === “always considers operands of different types to be different.” The usual team rule is simple: use === and !== everywhere, unless you have a specific reason not to.

PHP has the same pair, and its == changed in PHP 8. The manual describes the old rule: “Prior to PHP 8.0.0, if a string is compared to a number or a numeric string then the string was converted to a number before performing the comparison.” That’s why 0 == "a" used to be true. Since PHP 8 it’s false, but numeric-looking strings are still compared as numbers:

var_dump(0 == "a");        // bool(false)  (true before PHP 8)
var_dump("1" == "01");     // bool(true)
var_dump("10" == "1e1");   // bool(true)
var_dump(null == false);   // bool(true)
var_dump(0 === "0");       // bool(false)

Same rule as JavaScript: reach for ===.

switch: many branches

When one value decides between several paths, a switch is often clearer than a chain of if/else if. Go’s version is a good example, because each case stops on its own:

switch day {
case "sat", "sun":
    fmt.Println("weekend")
case "mon":
    fmt.Println("monday")
default:
    fmt.Println("weekday")
}

In C and JavaScript, cases “fall through” into the next one unless you write break, and forgetting break is a classic bug. In Go it’s the other way around: you have to ask for it with fallthrough:

switch n {        // n is 1
case 1:
    fmt.Println("one")
    fallthrough
case 2:
    fmt.Println("two")
}
// one
// two

PHP has a classic switch (with break, and loose == comparison) and, since PHP 8, match. The manual: “Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==).” The difference shows up as soon as types mix:

$status = "1";
echo match ($status) { 1 => "int one", "1" => "string one", default => "other" };
// string one

switch ($status) { case 1: echo "switch matched int 1"; break; }
// switch matched int 1

Writing conditions people can read

Correct is the minimum. Readable is what keeps it correct later.

  • Name complex conditions. canCheckout := cartHasItems && paymentReady && !isBlocked reads better than three conditions inline in an if.
  • Return early. Handle the error or edge case first and return, so the main logic isn’t buried three levels deep:
def ship(order):
    if order is None:
        return "no order"
    if not order.paid:
        return "not paid"
    return "shipping"
  • Avoid double negatives. if not is_not_ready makes every reader stop and think. Rename the variable.
  • Compare explicitly when zero or empty is valid. if count is not None says something different from if count, and sometimes that difference is the bug.

Try it yourself

  1. In Python, print bool() of a few values: 0.0, "False", [[]], {}. Guess first.
  2. In your browser console, compare [] == false with Boolean([]). Then explain to yourself why both are true.
  3. Find a place in your own code that uses || or or for a default, and check whether 0 or "" could ever be a valid value there.
  4. Write the opposite of age >= 18 and has_id using De Morgan’s laws, then check it with a few values.

Summary

  • Boolean logic has three operations: and, or, not. De Morgan’s laws tell you how to negate combined conditions.
  • Python, JavaScript, and PHP treat some values as falsy; they don’t agree on all of them (empty arrays, the string "0"). Go accepts only real booleans.
  • and / or short-circuit and return one of their operands, which is handy for guards and defaults.
  • Defaulting with or / || replaces valid 0 and "". Use ?? in JavaScript or an explicit None check in Python.
  • In JavaScript and PHP, use === instead of ==; in PHP, prefer match over switch when types can mix.
  • Readable conditions: name them, return early, avoid double negatives.

References