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:
- condition: A boolean expression (or something that converts to boolean)
- ?: The question mark separates the condition from the true case
- exprIfTrue: The value/expression returned if the condition is truthy
- : The colon separates the true case from the false case
- 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.