The ternary operator condition ? a : b returns a when the condition is truthy and b otherwise. It's the only JavaScript operator with three operands, and it's an expression: it produces a value you can assign, return or put inside a template string or JSX. There is no ternary without else: leaving out the : b part is a SyntaxError. When you only care about the true case, use if or && instead.
Tested with: Node.js 20.20, Chromium 156 and WebKit 27.2 (Safari's engine), and React 19.3's server renderer for the JSX cases, October 2026. Error messages are copied from those runs.
Syntax
condition ? valueIfTrue : valueIfFalse
const score = 75;
const result = score >= 60 ? "Pass" : "Fail"; // "Pass"It's equivalent to this if/else, in one line:
let result;
if (score >= 60) {
result = "Pass";
} else {
result = "Fail";
}"Truthy" means anything except false, 0, "", null, undefined and NaN. Reference: conditional operator on MDN.
Ternary Without Else: What to Use Instead
JavaScript requires both branches:
const status = temperature > 25 ? "Hot";
// SyntaxError: Unexpected token ';' (Chrome, Node.js)
// SyntaxError: Unexpected token ';'. Expected ':' in ternary operator. (Safari)(If you see "Unexpected token" errors elsewhere, our Unexpected token guide lists the other causes.) Pick the replacement by what you want to happen when the condition is false:
const isLoggedIn = true;
const temperature = 30;
let status = "Normal";
// 1. Run something only when true: use if (clearest) …
if (isLoggedIn) showDashboard();
// … or && for a short expression
isLoggedIn && showDashboard();
// 2. Set a value only when true: keep the old value otherwise
status = temperature > 25 ? "Hot" : status;
// 3. A value or nothing: be explicit about the "nothing"
const badge = isLoggedIn ? "Member" : null;
function showDashboard() {
console.log("Dashboard shown");
}
console.log(status, badge); // "Hot" "Member"| You want… | Use | Example |
|---|---|---|
| To run code only if true | if (or &&) | if (isLoggedIn) showDashboard(); |
| To set a value only if true | Ternary that keeps the old value | status = hot ? "Hot" : status; |
| A value or nothing | Ternary with an explicit null | const badge = vip ? "VIP" : null; |
| A default when a value is missing | ?? (or ||) | const qty = input ?? 1; |
| To render something only if true (React) | A boolean && JSX | {count > 0 && <Badge />} |
isLoggedIn && showDashboard() works because && stops when the left side is falsy. It's fine in short expressions, but as a statement on its own line an if is clearer, and ESLint's no-unused-expressions rule flags the && version unless you enable allowShortCircuit.
Nested Ternaries (Multiple Conditions)
// Nested ternary, formatted one condition per line
const grade = (marks) =>
marks >= 80 ? "Excellent"
: marks >= 60 ? "Good"
: marks >= 40 ? "Average"
: "Unsatisfactory";
// Same logic with early returns: easier to extend and debug
function gradeFor(marks) {
if (marks >= 80) return "Excellent";
if (marks >= 60) return "Good";
if (marks >= 40) return "Average";
return "Unsatisfactory";
}
console.log(grade(85), grade(65), grade(45), grade(10));
console.log(gradeFor(85), gradeFor(65), gradeFor(45), gradeFor(10));Both versions printed "Excellent Good Average Unsatisfactory" for 85, 65, 45 and 10. A chained ternary is fine when it's formatted one condition per line and every branch is a simple value. Once a branch needs more than a value, or the conditions aren't a simple ladder, use if with early returns. Avoid nesting inside the true branch (a ? b ? x : y : z), which is hard to read either way.
Precedence: The Bug That Always Picks One Branch
const isMember = false;
"Total: " + isMember ? "$8" : "$10"; // "$8" ← wrong
"Total: " + (isMember ? "$8" : "$10"); // "Total: $10"
`Total: ${isMember ? "$8" : "$10"}`; // "Total: $10"The ternary has very low precedence, so "Total: " + isMember is evaluated first. The result, "Total: false", is a non-empty string and therefore truthy, so the expression always returns "$8". We confirmed this in all three engines. Wrap the ternary in parentheses, or use a template literal.
Ternary vs || and ??
const qty = 0;
qty || 1; // 1 ← 0 is falsy, so it's replaced
qty ?? 1; // 0 ← only null/undefined are replaced
const name = "";
name || "Guest"; // "Guest"
name ?? "Guest"; // ""
const user = null;
user ? user.name : "Anonymous"; // "Anonymous"
user?.name ?? "Anonymous"; // "Anonymous", shorterWhen the ternary is just "use this value if it exists, otherwise a default", ?? says it in fewer characters and doesn't treat 0 or "" as missing. Use || only when those should also fall back.
Ternary in React (JSX)
function Inbox({ count }) {
return (
<div>
{count && <p>You have {count} messages</p>} {/* count = 0 renders "0" */}
{count > 0 && <p>You have {count} messages</p>} {/* renders nothing */}
{count > 0 ? <p>You have {count} messages</p> : <p>No messages</p>}
</div>
);
}We rendered these with React 19.3: {count && <p>…</p>} with count = 0 produced <div>0</div>, a stray zero on the page. The same happens with {items.length && …} on an empty array. Use a real boolean (count > 0) or a ternary with null / an else branch. For a bigger React pattern built on conditional rendering, see useOptimistic.
More Useful Patterns
// Pick a function, then call it
(isAdmin ? showAdminPanel : showUserPanel)();
// Pick a CSS class
button.className = isActive ? "btn btn-active" : "btn";
// Pick an object property
const label = { small: "S", medium: "M", large: "L" }[size] ?? "M";A lookup object (the last example) often replaces a long ternary chain that maps one value to another.
What You Can't Put in a Ternary
// SyntaxError: statements like return can't go inside a ternary
isValid ? return data : throw new Error("Invalid");
// Return the ternary instead
return isValid ? data : null;Both branches must be expressions. return, throw (as a statement), break, let declarations and loops are statements, so Chrome reports Unexpected token 'return' and Safari Unexpected keyword 'return'. Return the whole ternary instead, or use if.
When to Use a Ternary (and When Not To)
| Use a ternary for | Use if/else for |
|---|---|
| Choosing between two values | Running several statements |
| Assignments, return values, template strings, JSX | Side effects (logging, API calls, DOM updates) |
| Short, readable conditions | Conditions that need comments to understand |
| One level, or a formatted ladder | Deep or irregular nesting |
FAQs
Can you use a ternary operator without else in JavaScript?
No. cond ? a without : b is a SyntaxError. Use if (cond) …, cond && …, or a ternary with an explicit null / unchanged value.
What is the ternary operator in JavaScript?
A conditional expression, condition ? valueIfTrue : valueIfFalse, that returns one of two values. It's often called the conditional operator.
Is the ternary operator faster than if/else?
No meaningful difference; engines optimize both. Choose based on readability.
Can I use multiple conditions in a ternary?
Yes, either combine them (a && b ? x : y) or chain ternaries one condition per line. For more than three or four branches, if or a lookup object reads better.
What's the difference between ?: and ??
?: picks between two values based on any condition. ?? returns the right side only when the left side is null or undefined.
Why does my React component render 0?
{count && <Component />} returns count itself when it's 0, and React renders numbers. Use {count > 0 && <Component />} or a ternary.
Related Articles
View allAbout Muhaymin Bin Mehmood
Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.




