JavaScript - Conditional (Ternary) Operator

Overview

Estimated time: 10–15 minutes

The ternary operator picks between two expressions based on a condition. Great for compact value selection.

Learning Objectives

  • Use cond ? a : b for simple conditional expressions.
  • Avoid deeply nested ternaries for readability.

Prerequisites

Examples

const sign = (x > 0 ? 1 : -1);
const color = isDark ? 'black' : 'white';

Common Pitfalls

  • Complicated nested ternaries harm readability; prefer if/else for complex branches.