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).

Frequently asked questions

How does Python handle truthiness?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Truthiness Gotchas" snippet in Python uses `# Falsy: None, False, 0, 0.0, '', [], {}, set()`.
Which code does the Python example use?
The "Truthiness Gotchas" snippet uses `# Falsy: None, False, 0, 0.0, '', [], {}, set()`, from the Common Mistakes section of the Python cheat sheet.
Which stacks cover "truthiness" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Truthiness Gotchas": 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.