Conditional expression

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Ternary Operator

JS · Control Flow
syntax
condition ? valueIfTrue : valueIfFalse
example
const age = 20;
const category = age >= 18 ? "adult" : "minor";
console.log(category); // "adult"

// Nested (use sparingly)
const tier = age >= 65 ? "senior" : age >= 18 ? "adult" : "minor";

Note Great for simple inline conditions. Avoid deeply nested ternaries -- they quickly become unreadable. Use if/else for complex logic.

PYPython

Conditional (Ternary) Expression

PY · Control Flow
syntax
value_if_true if condition else value_if_false
example
age = 20
status = "adult" if age >= 18 else "minor"
print(status)

# Nested (use sparingly)
label = "high" if age > 60 else "mid" if age > 30 else "young"
print(label)
output
adult
young

Note Nested ternaries hurt readability fast. If you need more than one level, use a regular if/elif chain instead.