Hiprup

What is the ternary operator?

The ternary operator is a compact one-line if/else that returns a value: condition ? valueIfTrue : valueIfFalse.

  • Returns a value — unlike if, it's an expression, so it can be assigned or embedded.

  • Use sparingly — great for simple choices; nested ternaries hurt readability.

Good for concise assignments; switch to a full if/else when the logic is complex.

// Basic usage
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';

// Inline in template literals
const message = `You are ${age >= 18 ? 'an adult' : 'a minor'}`;

// Nested (avoid — hard to read)
const grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'F';
// Better as if/else or object lookup:
const grades = { A: 90, B: 80, C: 70 };

// In function returns
const abs = (n) => n >= 0 ? n : -n;

// Conditional function calls
isValid ? process(data) : showError('Invalid data');

condition ? true : false replaces simple if/else. Clean for assignments and inline expressions.

Nested ternaries (grade example) should use if/else or lookup tables instead. Arrow functions with ternary (abs) provide concise one-liners.

Simple question but know when NOT to use it: nested ternaries are unreadable. Suggest object lookups or if/else for complex conditions.

The most common use: conditional assignment (const x = condition ? a : b).

What is the ternary operator? | Hiprup