The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you use it anywhere you need to choose between two values.
Table of Content
Understand the Ternary Operator in JavaScript
The ternary operator is a shortcut that replaces simple if-else statements. It checks a condition, then picks one of two values based on that.
Here is the syntax:
condition ? valueIfTrue : valueIfFalse;
This line returns valueIfTrue
when the condition is true. If false, it returns valueIfFalse
.
This operator has three parts:
- A condition you want to check
- A value to return if true
- A value to return if false
It returns one of the two values. You can use the result in assignments, expressions, or returns.
It makes your code shorter. You can handle a simple condition in one line instead of writing if and else. That keeps your logic easy to read when it stays simple.
Here is a quick example:
let age = 18;
let message = age >= 18 ? "Adult" : "Minor";
The condition checks if age is 18 or more. It returns “Adult” if true, or “Minor” if not.
let loggedIn = false;
let text = loggedIn ? "Logout" : "Login";
If the user is logged in, the button says “Logout.” Otherwise, it shows “Login.”
You can assign values based on a condition in one line:
let score = 70;
let status = score >= 60 ? "Pass" : "Fail";
This assigns “Pass” if the score is 60 or higher. Otherwise, it assigns “Fail.”
Chained Ternary Operators (Nested Conditions) in JavaScript
You can use ternary inside another ternary when you have more than two options:
let grade = 85;
let result = grade >= 90 ? "A" :
grade >= 80 ? "B" :
grade >= 70 ? "C" : "F";
It checks each condition in order. The first true one returns its value. Keep it clean or move to if-else if it gets hard to read.
Ternary Operator vs If-Else: When to Use What?
The ternary operator works well when you need to choose between two values in a quick and simple way. It fits one-line decisions. But it has limits.
Here are the key differences and when to use each:
Use ternary operator when:
- You check one simple condition
- You return one of two values
- You want shorter, cleaner code
- You do not need side effects or extra steps
Here is an example:
let score = 80;
let result = score >= 50 ? "Pass" : "Fail";
This does one check and returns one of two values. No need for if-else here.
Use if-else statement when:
- You have many conditions
- You need more than one line of logic
- You need to run extra code, not just return values
- Readability matters more than short code
For example:
let score = 80;
let result;
if (score >= 90) {
result = "A";
} else if (score >= 75) {
result = "B";
} else {
result = "C";
}
This logic checks multiple levels. It needs if-else to stay clear.
Use ternary to keep code short when the logic is simple. Use if-else to stay readable when the logic grows. For long or nested checks, if-else avoids confusion. For fast value selection, ternary saves space.
Examples of Ternary Operator in JavaScript
Ternary Operator Example: Check User Status:
let isOnline = true;
let status = isOnline ? "Online" : "Offline";
This checks if the user is online. It returns “Online” when true, or “Offline” when false. One line replaces an if-else block.
Ternary Operator Example: Set Weather Label:
let temp = 30;
let weather = temp > 25 ? "Hot" : "Cool";
It compares temperature with 25. If above, it says “Hot”. If not, it says “Cool”.
Membership Fee Example:
let isMember = false;
let fee = isMember ? "$10" : "$20";
This checks membership status. Members pay $10. Others pay $20.
Reward Based on Points:
let points = 45;
let reward = points >= 50 ? "Gold" : "Silver";
Points decide the reward level. “Gold” needs 50 or more. Lower scores get “Silver”.
Vote Count Label:
let votes = 0;
let message = votes === 1 ? "1 vote" : votes + " votes";
It handles singular and plural forms. When votes equal 1, it shows “1 vote”. Otherwise, it adds “votes”.
Nested Grade Check:
let score = 88;
let grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
It checks two conditions in one line. Score 90+ gives “A”. Score 80+ gives “B”. Others get “C”.
Inline Use in Function Return:
function getColor(code) {
return code === "red" ? "#FF0000" :
code === "green" ? "#00FF00" :
"#000000";
}
This returns a color code. It matches “red” and “green”. Anything else returns black.
Assign Message Based on Role:
let role = "admin";
let access = role === "admin" ? "Full Access" : "Limited Access";
The role decides the access level. Admins get full control. Others get limited rights.
Handle Empty Input:
let input = "";
let display = input ? input : "No data found";
This shows user input if available. If empty or false, it shows a default message.
Wrapping Up
In this article, you learned how the ternary operator works and why it helps simplify decisions. You saw syntax, real examples, and when to avoid it. Here is a quick recap:
- Use
condition ? trueValue : falseValue
to replace short if-else - It keeps your code short when the logic is simple
- You can nest ternary checks, but keep them readable
- Use if-else when the logic becomes long or complex