Syntax
condition ? valueIfTrue : valueIfFalseExamples
Basic Ternary
Assigning a value based on a condition in a single line.
const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"Ternary in JSX-style Rendering
A common pattern for conditional rendering in template-like code.
const isLoggedIn = true;
const message = isLoggedIn
? `Welcome back!`
: `Please log in.`;
console.log(message);
// Nested ternaries are possible but hurt readability - use sparingly
const grade = 85;
const letter = grade >= 90 ? "A" : grade >= 80 ? "B" : grade >= 70 ? "C" : "F";Best practices
- Use the ternary operator for simple, single-condition value assignments - reach for if...else when logic gets more complex
- Avoid deeply nested ternaries, as they quickly become hard to read - a switch or if/else chain is often clearer
- Wrap ternaries in parentheses when used inside template literals or JSX for clarity
- Remember it is an expression (produces a value), unlike if/else which is a statement
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification