The Ternary Operator
The ternary operator is an if and else squeezed into a single expression that produces a value.
condition ? whenTrue : whenFalse produces a value, so it can be assigned, returned or dropped into a template literal. Good for choosing between two values, poor for running two branches of logic.
EXERCISE
1An if That Produces a Value
The difference between a ternary and an if is not length, it is that a ternary evaluates to something you can use.
if is a statement: it does something. A ternary is an expression: it produces a value.
The shape:
const age = 20;
const status = age >= 18 ? "adult" : "minor";
// ^condition^ ^if true^ ^if false^
console.log(status); // adult
Which is why this works and the if version does not:
// You cannot assign an if:
// const status = if (age >= 18) { "adult" } else { "minor" };
// SyntaxError
// The if version needs a let and four more lines:
let status;
if (age >= 18) {
status = "adult";
} else {
status = "minor";
}
// The ternary does it in one, and keeps the const:
const status2 = age >= 18 ? "adult" : "minor";
And why it fits inside other expressions:
const count = 1;
console.log(`You have ${count} ${count === 1 ? "message" : "messages"}`);
// You have 1 message
function fee(isMember) {
return isMember ? 0 : 250;
}
console.log(fee(true)); // 0
console.log(fee(false)); // 250
Reach for a ternary when you are choosing a value, and for an if when you are choosing an action. A ternary that assigns one variable is the clearest way to write that. A ternary whose branches both call functions for their side effects is an if wearing a disguise.
EXERCISE
2Where Ternaries Go Wrong
The operator is compact, and compact code can hide a lot, so a few shapes are worth avoiding on purpose.
Nesting is legal and hard to read:
const score = 72;
// Nested: technically fine, genuinely unpleasant
const grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : "F";
console.log(grade); // C
// The else-if chain says the same thing and can be scanned:
let grade2;
if (score >= 90) grade2 = "A";
else if (score >= 75) grade2 = "B";
else if (score >= 60) grade2 = "C";
else grade2 = "F";
One level of nesting is usually tolerable. Three is a chain pretending to be an expression.
Using it for side effects wastes the one thing it is good at:
const isAdmin = true;
// The result is thrown away, so the expression bought you nothing:
isAdmin ? console.log("Admin view") : console.log("User view");
// Say it as a decision, because that is what it is:
if (isAdmin) {
console.log("Admin view");
} else {
console.log("User view");
}
Comparing a boolean to produce a boolean:
const isReady = true;
const canStart = isReady ? true : false; // says nothing new
const canStart2 = isReady; // the same value
const isEmpty = items.length === 0 ? true : false;
const isEmpty2 = items.length === 0; // already a boolean
Pro Tip: If both branches of your ternary are
trueandfalse, delete the ternary, because the condition already produced exactly that. It is one of the most common pieces of redundant code in JavaScript, and spotting it is a quick way to make a file shorter and clearer at the same time.
EXERCISE
3Ternaries in the Places You Will Meet Them
Three patterns account for most real-world ternaries, and recognising them makes unfamiliar code much easier to read.
Choosing a label or a class name:
const isActive = true;
const count = 0;
const label = isActive ? "Online" : "Offline";
const cssClass = count > 0 ? "badge badge-alert" : "badge";
console.log(label); // Online
console.log(cssClass); // badge
Handling singular and plural:
function describe(n) {
return `${n} item${n === 1 ? "" : "s"}`;
}
console.log(describe(1)); // 1 item
console.log(describe(3)); // 3 items
console.log(describe(0)); // 0 items
Supplying a safe value before using it:
const user = { name: null };
const display = user.name ? user.name : "Anonymous";
console.log(display); // Anonymous
// Two shorter ways you have already seen:
const display2 = user.name || "Anonymous"; // falls back on any falsy
const display3 = user.name ?? "Anonymous"; // falls back on null/undefined only
// For this case all three agree. When the value could be 0 or "",
// they do not, and ?? is the one that behaves.
A shape you will see constantly in React and similar libraries:
const items = [];
const message = items.length === 0
? "No results found"
: `Found ${items.length} results`;
console.log(message); // No results found
// Split across lines like this, a ternary stays readable
// even when the branches are long.
When a ternary gets long, break it across three lines with the ? and : starting their own lines. It keeps the single-expression benefit while giving your eye the same structure an if-else would have, and it is the formatting that every automatic formatter will produce for you anyway.
