Truthiness

2 snippets across 2 stacks — Python, TypeScript

PYPython

Truthiness Gotchas

PY · Common Mistakes
syntax
# Falsy: None, False, 0, 0.0, '', [], {}, set()
example
def process(data=None):
    # WRONG: if not data
    # This also catches empty list [], 0, and ""
    if not data:
        print("No data")  # Triggered by empty list too!

    # CORRECT: if data is None
    if data is None:
        print("Data is None")

process([])   # Might not intend to reject []
process(None)
process(0)
output
No data
No data
Data is None
No data

Note Empty collections, zero, empty string, and None are all falsy. When you specifically mean 'no value provided', check 'is None' rather than relying on truthiness.

TSTypeScript

Truthiness Narrowing

TS · Type Guards & Narrowing
syntax
if (value) { ... } // narrows out null, undefined, 0, "", false
example
function printLength(input: string | null | undefined) {
  if (input) {
    // input is narrowed to string (null and undefined excluded)
    console.log(`Length: ${input.length}`);
  } else {
    console.log("No input provided");
  }
}

// Combining with logical operators
function getDisplayName(first?: string, last?: string): string {
  return (first && last) ? `${first} ${last}` : first ?? last ?? "Anonymous";
}
output
// Truthiness checks exclude null, undefined, and falsy values

Note Truthiness narrowing also excludes 0, empty string, and false — which may not be what you want. If 0 or "" are valid values, check explicitly for null/undefined instead: if (value != null) or if (value !== undefined).