The JavaScript ternary operator is written condition ? valueIfTrue : valueIfFalse. It evaluates the condition and gives back one of the two expressions, which makes it a compact replacement for a simple if...else that only assigns or returns a value.
According to MDN, it is the only JavaScript operator that takes three operands, which is where the name "ternary" comes from. Its formal name is the conditional operator.
JavaScript ternary operator syntax
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
The three parts are:
- Condition: an expression whose value is tested, placed before the
?. - Value if truthy: the expression between
?and:, used when the condition is truthy. - Value if falsy: the expression after
:, used when the condition is falsy.
Only the chosen branch is evaluated. If the condition is truthy, the expression after the colon never runs, and the other way round. That matters when a branch calls a function or reads a property that would throw on the wrong input.
All three parts are required. There is no ternary form without the : exprIfFalse part, so a one-sided check needs an if statement instead.
What counts as true or false in the condition
The condition does not have to be a boolean. MDN lists the falsy values: besides false, they are null, NaN, 0, the empty string "", and undefined. Anything else is truthy, including the string "0", the string "false", an empty array and an empty object.
const items = [];
console.log(items ? "has items" : "no items"); // "has items" (an empty array is truthy)
console.log(items.length ? "has items" : "no items"); // "no items"
The first line is a common mistake. If you mean "is the array non-empty", test items.length or items.length > 0, not the array itself.
Ternary vs if...else
MDN describes the ternary as frequently used as an alternative to if...else. The difference is that if is a statement and the ternary is an expression. An expression has a value, so it can sit anywhere a value can: on the right of const, after return, inside a function call, or inside a template literal.
// if...else: needs a mutable variable
let label;
if (isAdmin) {
label = "Admin";
} else {
label = "Member";
}
// ternary: one expression, and label can be const
const label = isAdmin ? "Admin" : "Member";
That is the strongest reason to use it. Being able to write const instead of let means the variable cannot be reassigned by mistake later.
Inside a template literal, wrap the ternary in the ${ } placeholder:
const count = 1;
console.log(`You have ${count} ${count === 1 ? "message" : "messages"}`);
// You have 1 message
Use the ternary to choose a value. Do not use it to run actions. Something like ok ? save() : showError() works, but it hides what is really an if statement, and the next reader has to work out that the result is thrown away.
Handling missing values with a ternary
MDN's own example guards against a null object:
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
Because only the chosen branch runs, person.name is never read when person is null, so no TypeError is thrown.
Chaining ternaries
The operator is right-associative, so you can chain it. MDN shows it as the equivalent of an if ... else if ... else chain:
function describeTemperature(celsius) {
return celsius < 0 ? "freezing"
: celsius < 15 ? "cold"
: celsius < 25 ? "mild"
: "warm";
}
describeTemperature(-3); // "freezing"
describeTemperature(20); // "mild"
Put each condition on its own line, with the : at the start of the line, so the shape of the chain is visible. The conditions are checked from the top and the first truthy one wins, exactly as in an else if chain.
Nested ternaries: when to stop
A chain is one flat sequence of tests. A nested ternary puts a ternary inside one of the branches in a way that is not a simple chain, and it gets hard to read quickly. ESLint's no-nested-ternary rule exists for this reason: "Nesting ternary expressions can make code more difficult to understand." The rule flags this:
const thing = foo ? bar : baz === qux ? quxx : foobar;
and suggests an if / else if / else that assigns to a variable instead. The rule has no options, so whether you enable it is a team choice. A practical limit: if you cannot read the expression aloud in one breath, or it needs more than three outcomes, use if statements, a lookup object, or a small function with early return lines.
Operator precedence pitfalls
The ternary binds loosely. Comparison operators, +, && and || all bind tighter than ?:, so they are evaluated as part of the condition. That is why age >= 21 ? ... : ... works without brackets. The same rule causes a classic bug when you build a string with +:
const n = 3;
const wrong = "Count: " + n > 1 ? "many" : "one";
console.log(wrong); // "one"
JavaScript reads the condition as ("Count: " + n) > 1. The string "Count: 3" converts to NaN for the comparison, NaN > 1 is false, and the result is "one", which is wrong for n = 3. Brackets fix it:
const right = "Count: " + (n > 1 ? "many" : "one");
console.log(right); // "Count: many"
When a ternary sits next to another operator, add brackets, even where they are not strictly needed. It costs two characters and removes the question. Conditions often compare values too, and == vs === in JavaScript explains which equality operator to use there.
Ternary vs ?? and ||
A frequent use of the ternary is supplying a default: value ? value : "default". That form treats every falsy value as missing, including 0 and "", which are often legitimate. MDN's page on nullish coalescing explains that || returns the right-hand side for any falsy left operand, while ?? only does so for null or undefined.
Expression with count = 0 | Result | Why |
|---|---|---|
count ? count : 42 | 42 | 0 is falsy |
count || 42 | 42 | 0 is falsy |
count ?? 42 | 0 | 0 is neither null nor undefined |
count !== undefined ? count : 42 | 0 | explicit undefined check |
If the intent is "use this unless it is missing", write ??. Keep the ternary for the cases where the choice depends on a real condition, such as a comparison or a flag.
When to use a ternary, and when not to
- Good fit: two possible values, a short condition, and the result is assigned, returned or interpolated.
- Poor fit: branches that have side effects, branches long enough to wrap across several lines, or more than a few chained conditions.
- Formatting: if the whole expression does not fit on one line, break before
?and before:, and indent both.
const message = isLoggedIn
? `Welcome back, ${user.name}`
: "Please sign in";
If you are comparing the readability of this with a lookup table, remember that an object like { low: 1, medium: 5, high: 10 }[level] is often clearer than a chain of three ternaries testing level for equality.
Frequently asked questions
- Is the JavaScript ternary operator the same as an if statement?
- It does the same branching, but it is an expression, so it produces a value you can assign, return or pass to a function. An if statement produces no value. Use the ternary when you are choosing between two values, and if/else when each branch needs to run several statements.
- Can I use a ternary without the else part?
- No. The syntax requires all three operands: condition ? exprIfTrue : exprIfFalse. If you only want to act when the condition is true, use an if statement, or condition && value when you want a value that is falsy otherwise.
- What is the difference between ?: and ?? in JavaScript?
- The ternary ?: picks one of two expressions based on any condition. The nullish coalescing operator ?? returns its right side only when the left side is null or undefined. So count ?? 42 keeps a count of 0, while count ? count : 42 replaces it with 42.
- Can you chain more than one ternary?
- Yes. The operator is right-associative, so a ? x : b ? y : z reads like an if, else if, else chain. Format each branch on its own line, and switch to if/else once you have more than two or three conditions.