← Back to Roadmap

Conditional (Ternary) Operator

Easy

In plain terms

The ternary operator condition ? valueIfTrue : valueIfFalse is a shorthand for if-else when assigning a value. Use it for simple conditionals; prefer if-else for complex logic.

What you need to know

  • condition ? a : b
  • Returns one of two expressions
  • Can be nested but keep simple

Try it yourself

Copy the code below and run it in your browser console or a code editor:

const age = 18;
const status = age >= 18 ? 'adult' : 'minor';

// Nested (use sparingly)
const score = 85;
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';

// With function calls
const message = isLoggedIn ? getUserName() : 'Guest';

Learn more

Dive deeper with these trusted resources: