Docs

3.6-Ternary-Operator

3.6 Ternary Operator

Table of Contents

  1. •What Is the Ternary Operator
  2. •Basic Syntax
  3. •Comparison with if-else
  4. •Nested Ternary Operators
  5. •Common Use Cases
  6. •Best Practices
  7. •Anti-Patterns to Avoid

What Is the Ternary Operator

The ternary operator (also called the conditional operator) is JavaScript's only operator that takes three operands. It provides a concise way to write simple conditional expressions.

Why "Ternary"?

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Operator Types by Number of Operands                       │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                             │
│  UNARY (1 operand):      !true, -5, typeof x               │
│                                                             │
│  BINARY (2 operands):    a + b, x && y, n > 5              │
│                                                             │
│  TERNARY (3 operands):   condition ? valueIfTrue : valueIfFalse │
│                                                             │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Basic Syntax

Structure

condition ? expressionIfTrue : expressionIfFalse;

Visual Breakdown

      condition   ?   valueIfTrue   :   valueIfFalse
          │       │        │        │         │
          │       │        │        │         └─── Returned if condition is FALSE
          │       │        │        └───────────── Separator
          │       │        └────────────────────── Returned if condition is TRUE
          │       └─────────────────────────────── Operator symbol
          └─────────────────────────────────────── Any expression that evaluates to boolean

Basic Example

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

console.log(status); // "adult"

Execution Flow

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│                                                             │
│   age >= 18     ?     "adult"     :     "minor"            │
│       │                  │                   │              │
│       ā–¼                  │                   │              │
│    [true]               │                   │              │
│       │                  │                   │              │
│       └──────────► Return "adult"          │              │
│                                            (skipped)        │
│                                                             │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Comparison with if-else

Equivalent Forms

Ternaryif-else
const result = condition ? a : b;let result; if (condition) { result = a; } else { result = b; }

Side-by-Side Comparison

// Using if-else
let message;
if (hour < 12) {
  message = 'Good morning';
} else {
  message = 'Good afternoon';
}

// Using ternary (same result)
const message = hour < 12 ? 'Good morning' : 'Good afternoon';

Key Differences

AspectTernaryif-else
Return ValueAlways returns a valueStatement, no return
Use in ExpressionsYes (inside JSX, template literals)No
Line Count1 lineMultiple lines
ReadabilityGood for simple conditionsBetter for complex logic
Side EffectsShould be avoidedCommon use case

When Ternary Shines

// Template literals
const greeting = `Hello, ${isLoggedIn ? username : 'Guest'}!`;

// JSX (React)
return <div>{isLoading ? <Spinner /> : <Content />}</div>;

// Default values
const displayName = name ? name : 'Anonymous';

// Function arguments
console.log(isDebug ? detailedError : shortError);

Nested Ternary Operators

Multiple Conditions

You can nest ternary operators to handle multiple conditions:

const score = 85;

// Nested ternary
const grade =
  score >= 90
    ? 'A'
    : score >= 80
    ? 'B'
    : score >= 70
    ? 'C'
    : score >= 60
    ? 'D'
    : 'F';

console.log(grade); // "B"

Execution Flow for Nested

score >= 90 ? "A"                    // Is 85 >= 90? No
          : score >= 80 ? "B"        // Is 85 >= 80? Yes → Return "B"
                      : score >= 70 ? "C"
                                  : score >= 60 ? "D"
                                              : "F"

Formatting Nested Ternaries

// Style 1: Each condition on new line (most readable)
const result = condition1
  ? value1
  : condition2
  ? value2
  : condition3
  ? value3
  : defaultValue;

// Style 2: Aligned colons
const type =
  value === null ? 'null' : value === undefined ? 'undefined' : typeof value;

// Style 3: Inline (only for 2 simple conditions)
const size = width > 1200 ? 'large' : width > 768 ? 'medium' : 'small';

Equivalent if-else-if

// Ternary
const category =
  age < 13 ? 'child' : age < 20 ? 'teenager' : age < 65 ? 'adult' : 'senior';

// Equivalent if-else-if
let category;
if (age < 13) {
  category = 'child';
} else if (age < 20) {
  category = 'teenager';
} else if (age < 65) {
  category = 'adult';
} else {
  category = 'senior';
}

Common Use Cases

1. Default Values

// Simple default
const username = inputName ? inputName : 'Guest';

// Better: nullish coalescing for null/undefined
const username = inputName ?? 'Guest';

// But ternary for truthy check
const displayCount = count ? count : 'No items';

2. Conditional Assignment

// Toggle state
const newState = isOpen ? false : true;
// Better: const newState = !isOpen;

// Choose between two values
const theme = isDarkMode ? darkTheme : lightTheme;
const discount = isPremium ? 0.2 : 0;

3. Conditional Function Calls

// Call different functions based on condition
const handler = isAsync ? handleAsync : handleSync;

// Different method calls
const result = useCache ? getCached(id) : fetchFresh(id);

4. String Interpolation

const userInfo = `Welcome, ${user ? user.name : 'Guest'}!`;

const statusText = `Status: ${isOnline ? 'Online' : 'Offline'}`;

const itemText = `${count} item${count !== 1 ? 's' : ''}`;

5. Object Property Selection

const config = {
  mode: isProduction ? 'production' : 'development',
  debug: isProduction ? false : true,
  apiUrl: isProduction ? PROD_URL : DEV_URL,
};

6. Conditional Rendering (React/JSX)

// In JSX
return <div>{isLoggedIn ? <Dashboard user={user} /> : <LoginForm />}</div>;

// Inline conditional
return <span className={isActive ? 'active' : 'inactive'}>Status</span>;

7. Conditional Array/Object Inclusion

// Conditional array element
const items = [
  'always included',
  condition ? 'sometimes included' : null,
].filter(Boolean);

// Conditional object property
const user = {
  name: 'John',
  ...(isAdmin ? { role: 'admin' } : {}),
};

Best Practices

āœ… DO: Keep It Simple

// Good: Simple, easy to read
const access = isAdmin ? 'full' : 'limited';

// Good: Clear intent
const greeting = isEvening ? 'Good evening' : 'Good day';

āœ… DO: Use for Pure Expressions

// Good: Returns a value based on condition
const displayName = user.nickname ? user.nickname : user.fullName;

// Good: Inline in template
console.log(`Found ${count} result${count === 1 ? '' : 's'}`);

āœ… DO: Format Nested Ternaries Clearly

// Good: Well-formatted nested ternary
const priority =
  level === 'critical' ? 1 : level === 'high' ? 2 : level === 'medium' ? 3 : 4;

āœ… DO: Use Parentheses When Needed

// Good: Parentheses clarify precedence
const message = 'Status: ' + (isActive ? 'Active' : 'Inactive');

// Good: In complex expressions
const result = baseValue + (hasBonus ? bonus : 0) * multiplier;

Anti-Patterns to Avoid

āŒ DON'T: Use for Side Effects

// Bad: Side effects in ternary
isValid ? saveData() : showError();

// Good: Use if-else for side effects
if (isValid) {
  saveData();
} else {
  showError();
}

āŒ DON'T: Nest Too Deeply

// Bad: Too nested, hard to read
const result = a ? (b ? (c ? d : e) : f) : g ? h : i;

// Good: Use if-else or switch for complex logic
let result;
if (a) {
  result = b ? (c ? d : e) : f;
} else {
  result = g ? h : i;
}

āŒ DON'T: Use When if-else is Clearer

// Bad: Complex conditions
const action =
  user.isAdmin && !user.suspended
    ? permissions.includes('delete')
      ? 'delete'
      : 'edit'
    : 'view';

// Good: if-else is clearer
let action;
if (user.isAdmin && !user.suspended) {
  action = permissions.includes('delete') ? 'delete' : 'edit';
} else {
  action = 'view';
}

āŒ DON'T: Forget It's an Expression

// Bad: Trying to use as statement
isCondition ? doSomething() : null; // Unnecessary

// Good: Just use if
if (isCondition) {
  doSomething();
}

āŒ DON'T: Return Boolean Literals

// Bad: Redundant ternary
const isAdult = age >= 18 ? true : false;

// Good: The condition already returns boolean
const isAdult = age >= 18;

// Bad: Negation with ternary
const isMinor = age >= 18 ? false : true;

// Good: Use negation
const isMinor = age < 18;
// Or: const isMinor = !(age >= 18);

Summary

ConceptDescription
Syntaxcondition ? valueIfTrue : valueIfFalse
ReturnsAlways returns one of the two values
Use CasesSimple conditionals, inline expressions, JSX
NestingPossible but use carefully
Best ForPure expressions without side effects
Avoid ForComplex logic, side effects, deep nesting

Decision Guide

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  Should I use a ternary operator?                           │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                                                             │
│  Is it a simple true/false choice?                         │
│    ā”œā”€ā”€ YES: Is it returning a value (not side effect)?    │
│    │         ā”œā”€ā”€ YES: Use ternary āœ“                        │
│    │         └── NO: Use if-else                           │
│    └── NO: Does it have 2-3 conditions?                    │
│             ā”œā”€ā”€ YES: Consider formatted nested ternary     │
│             └── NO: Use if-else or switch                  │
│                                                             │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Next Steps

After mastering the ternary operator, proceed to:

  1. •3.7 Spread Operator - Expanding arrays and objects
  2. •Practice using ternary in template literals
  3. •Combine with nullish coalescing for robust defaults
.6 Ternary Operator - JavaScript Tutorial | DeepML