Inline if

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.

Frequently asked questions

How does JavaScript handle inline if?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Ternary Operator" snippet in JavaScript uses `condition ? valueIfTrue : valueIfFalse`.
Which code does the JavaScript example use?
The "Ternary Operator" snippet uses `condition ? valueIfTrue : valueIfFalse`, from the Control Flow section of the JavaScript cheat sheet.
Which stacks cover "inline if" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Ternary Operator": Great for simple inline conditions. Avoid deeply nested ternaries -- they quickly become unreadable. Use if/else for complex logic.