- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Ternary Operator: Syntax, Usage, and Examples
The JavaScript ternary 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.
How to Use the JavaScript Ternary Operator
The general syntax of the ternary operator in JavaScript looks like this:
condition ? expressionIfTrue : expressionIfFalse;
Here’s a basic example:
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:
Assign a Value Conditionally
let isMember = true;
let discount = isMember ? 0.1 : 0;
console.log(discount); // 0.1
Assigning based on a boolean value becomes quick and readable.
Replace a Simple if...else Statement
Instead of this:
if (score > 50) {
result = "Pass";
} else {
result = "Fail";
}
Use this:
let result = score > 50 ? "Pass" : "Fail";
This reduces lines of code while keeping the logic clear.
Use Inside JSX or Template Literals
The ternary operator works great in inline expressions for UI logic:
let isLoggedIn = false;
let message = `Status: ${isLoggedIn ? "Online" : "Offline"}`;
You can dynamically generate strings based on conditions.
Examples of Ternary Operators JavaScript
Short Message Based on Boolean
let subscribed = true;
console.log(subscribed ? "Welcome back!" : "Please subscribe.");
Simple checks like these are perfect for ternary expressions.
Nested Ternary Operator
You can chain ternaries, but readability becomes a concern:
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.
Ternary in Function Return
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:
isLoggedIn ? return true : return false; // ❌ Invalid
Correct:
return isLoggedIn ? true : false; // ✅ Valid
Use in Default Value Assignments
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
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:
{isLoading ? <Spinner /> : <Content />}
Ternaries allow inline rendering logic in component templates.
Avoid Overuse or Over-Nesting
This is technically valid:
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
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:
let status;
if (value === 1) {
status = "On";
} else {
status = "Off";
}
Using ternary:
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:
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.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.