Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

9. Only nil and false are falsy

  • Status: Accepted
  • Date: 2026-09-02

Context

if, while, and, or, and not need a rule for which values count as true. Two traditions:

  • Minimal (Lua, Ruby-ish): only a dedicated "nothing" value and false are falsy; everything else, including 0 and "", is truthy.
  • Extended (Python, JavaScript, C): 0, 0.0, "", [], {}, and nil are all falsy.

The extended rule is convenient (if items: to mean "non-empty") but it conflates "absent" with "present but empty", which is a well-known source of bugs — a function that returns a count of 0 and one that returns "no answer" become indistinguishable in a condition.

Decision

Exactly two values are falsy: nil and false. Every other value — 0, 0.0, "", [], {}, every instance — is truthy.

To test emptiness, write it: if items.len() > 0:.

and and or return one of their operands (not a coerced boolean), following short-circuit evaluation. not returns a genuine true/false.

Consequences

  • One sentence defines the whole rule. Easy to teach, nothing to look up.
  • if x: where x might be 0 does what a reader expects (0 is a value).
  • Slightly more typing for the common "is this collection non-empty" check. Judged a good trade: the explicit form is also clearer.
  • and/or returning operands enables name or "default", which is idiomatic and does not misfire on 0/"" the way the Python rule can.

Alternatives considered

  • Python-style extended truthiness. Convenient but semantically muddy; 0/""/empty-collection falsiness causes real defects.
  • Strict: condition must be a bool, everything else is a type error. Safest, but verbose in a dynamically typed scripting language and against the language's lightweight feel. May be reconsidered if a type checker is ever added.