Course contentsShow
← JavaScript
Lesson 227 of 2,7236. Booleans and ConditionalsFree lesson

The Ternary Operator Syntax

Learn the compact `condition ? exprIfTrue : exprIfFalse` syntax for conditional expressions.

The Ternary Operator Syntax

You'll learn how to write compact conditional expressions using JavaScript's ternary operator—a one-liner alternative to if...else.

What Is the Ternary Operator?

The ternary operator is JavaScript's only operator that takes three operands. It provides a shorthand way to write simple conditional logic in a single expression. Instead of writing multiple lines with if and else, you can express "if this condition is true, use this value; otherwise, use that value" in one readable line.

The Syntax

condition ? exprIfTrue : exprIfFalse

Here's how it works:

  1. condition: A boolean expression (or something that converts to boolean)
  2. ?: The question mark separates the condition from the true case
  3. exprIfTrue: The value/expression returned if the condition is truthy
  4. : The colon separates the true case from the false case
  5. exprIfFalse: The value/expression returned if the condition is falsy

Examples

let age = 20;
let canVote = age >= 18 ? true : false;
// canVote is true

let score = 85;
let grade = score >= 90 ? "A" : "B";
// grade is "B"

let hasAccount = false;
let message = hasAccount ? "Welcome back!" : "Please sign up";
// message is "Please sign up"

Think of It Like a Fork in the Road

The ternary operator is like standing at a fork: you check the sign (condition), then take the left path (true expression) or right path (false expression). You always end up with exactly one result.

Key Takeaway: The ternary operator condition ? exprIfTrue : exprIfFalse lets you write concise conditional expressions that evaluate to one of two values based on whether the condition is truthy or falsy.