JAVASCRIPT
JavaScript Ternary Operator: Syntax, Usage, and Examples
The JavaScript ternary operator, also known as the conditional operator, offers a quick and compact way to write conditional expressions. Instead of using a full if...else statement, you can evaluate a condition and return a value in a single line.
The ternary operator JavaScript syntax is especially useful for assigning values or returning expressions based on a condition—making your code cleaner and more expressive. For any beginner learning JavaScript, mastering using ternary operators is essential for writing concise code.
Learn JavaScript on Mimo
How to Use the JavaScript Ternary Operator
The general syntax of the ternary operator in JavaScript looks like this:
JSX
condition ? expressionIfTrue : expressionIfFalse;
The question mark (?) and colon (:) are the key symbols that make up this conditional operator. The syntax uses three operands: the condition, the first expression, and the second expression.
Here’s a basic example:
JSX
let age = 18;
let access = age >= 18 ? "Granted" : "Denied";
console.log(access); // "Granted"
If the condition is true, the first expression runs. If it's false, the second one runs.
When to Use the Ternary Operator JavaScript
The ternary operator is ideal when you want to work with truthy and falsy values efficiently.
Assign a Value Conditionally
JSX
let isMember = true;
let discount = isMember ? 0.1 : 0;
console.log(discount); // 0.1
Assigning based on a boolean value becomes quick and readable. This pattern is common during variable initialization.
Replace a Simple if...else Statement
Instead of this:
JSX
if (score > 50) {
result = "Pass";
} else {
result = "Fail";
}
Use this:
JSX
let result = score > 50 ? "Pass" : "Fail";
This reduces lines of code while keeping the logic clear, similar to patterns found in Java and other programming languages.
Use Inside JSX or Template Literals
The ternary operator works great in inline expressions for UI logic:
JSX
let isLoggedIn = false;
let message = `Status: ${isLoggedIn ? "Online" : "Offline"}`;
You can also dynamically generate strings based on conditions for HTML classes and CSS styling.
Examples of Ternary Operators JavaScript
Short Message Based on Boolean
JSX
let subscribed = true;
console.log(subscribed ? "Welcome back!" : "Please subscribe.");
Simple checks like these are perfect for ternary expressions and help with debugging by providing clear output.
Nested Ternary Operator
You can chain ternaries, but readability becomes a concern:
JSX
let score = 85;
let grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
console.log(grade); // "B"
Nested ternaries are valid, but keep them readable and only use them for straightforward logic. For more complex conditions, consider a switch statement instead.
Ternary in Function Return
JSX
function getStatus(user) {
return user.active ? "Active" : "Inactive";
}
This returns a value based on the condition without writing an if...else block.
Learn More About Ternary Operator in JavaScript
Ternary Operator Is an Expression
You can’t use return, break, or continue inside a ternary. It’s not a statement—it evaluates and returns a value.
Bad:
JSX
isLoggedIn ? return true : return false; // ❌ Invalid
Correct:
JSX
return isLoggedIn ? true : false; // ✅ Valid
Use in Default Value Assignments
JSX
let userInput = "";
let display = userInput ? userInput : "Default";
console.log(display); // "Default"
You can simplify that even further with logical OR (||), but ternary is more explicit.
Use with Functions or Calculations
JSX
let temp = 35;
let advice = temp > 30 ? "Stay hydrated" : "Nice weather";
console.log(advice); // "Stay hydrated"
The ternary operator is flexible enough to use with any expression that returns a value.
Use in JSX for Conditional Rendering
In frameworks like React, you often see:
JSX
{isLoading ? <Spinner /> : <Content />}
Ternaries allow inline rendering logic in component templates.
Avoid Overuse or Over-Nesting
This is technically valid:
JSX
let accessLevel = role === "admin" ? "Full Access" :
role === "user" ? "Limited Access" :
role === "guest" ? "Read Only" :
"No Access";
But it’s harder to read than a switch or if-else chain. When logic gets more complex, switch to clearer alternatives.
Combine with Template Literals for Dynamic Output
JSX
let mode = "dark";
let cssClass = `theme-${mode === "dark" ? "darkmode" : "lightmode"}`;
console.log(cssClass); // "theme-darkmode"
This makes dynamic class names or IDs easy to generate on the fly.
Compare with if...else
Using if...else:
JSX
let status;
if (value === 1) {
status = "On";
} else {
status = "Off";
}
Using ternary:
JSX
let status = value === 1 ? "On" : "Off";
Both work, but the second example uses less code and is more elegant for simple checks.
Side Effects in Ternary (Not Recommended)
You technically can run side effects:
JSX
isReady ? startProcess() : logError();
But readability suffers. If both branches involve side effects, consider using a traditional if-else.
The JavaScript ternary operator helps you write cleaner, more concise conditional logic. It's perfect for simple evaluations, variable assignments, and dynamic values in UI elements.
Whether you're formatting strings, toggling values, or writing compact return statements, mastering the ternary operator JavaScript pattern will make your code more expressive and maintainable. Just be careful with nested expressions—clarity always matters more than saving a few lines.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot