← JS Mastery | Module 2: Control Flow Ternary Operator & Short-Circuit Evaluation
Module 2

Ternary Operator & Short-Circuit Evaluation

⏱ 12 min read ● Beginner 🆓 Free

The Ternary Operator

The ternary operator is JavaScript's only 3-part operator. It's a compact way to write if/else expressions — especially useful when assigning a value conditionally.

// Syntax: condition ? valueIfTrue : valueIfFalse

const age = 20;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "adult"

// Compare to if/else:
let status2;
if (age >= 18) {
  status2 = "adult";
} else {
  status2 = "minor";
}
// Same result, but ternary is more concise for simple assignments

// In JSX/templates — very common:
const greeting = isLoggedIn ? `Welcome, ${user.name}!` : "Please log in";

// With functions:
const max = (a, b) => a > b ? a : b;
console.log(max(10, 20)); // 20

// Nested ternary — readable only for simple cases:
const score = 85;
const grade = score >= 90 ? "A" :
              score >= 80 ? "B" :
              score >= 70 ? "C" : "F";
// Readable with line breaks — avoid nesting deeper than this
⚠️ Don't Overuse

Ternary is great for simple conditional assignments. For complex logic with multiple statements, use if/else. Readability matters more than brevity.

Short-Circuit Patterns in Practice

// || for default values
const username = userInput || "Anonymous";
const port = process.env.PORT || 3000;

// && for conditional execution  
user.isLoggedIn && loadDashboard();  // only calls if logged in
config.debug && console.log("Debug mode:", data);

// ?? for null-safe defaults (only null/undefined, not 0 or "")
const timeout = config.timeout ?? 5000;
const retries = options.retries ?? 3;

// Chaining:
const displayName = user?.profile?.displayName 
  || user?.name 
  || "Anonymous User";

// Combining in React-style rendering patterns:
const element = items.length > 0 && items.map(item => item.name).join(", ");
// Returns false if empty (falsy), or the string if not

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Rewrite these if/else statements as ternary operators: (1) checking if a number is even or odd, (2) returning "yes" or "no" based on a boolean, (3) assigning a tax rate based on income bracket.

EXERCISE 2

Write a function that formats a user's name. If a display name exists, use it. Otherwise use firstName + lastName. If neither, return "Anonymous". Use ternary/nullish coalescing.

← Loops