Ternary Operators in JavaScript: A Simple Guide
Today, we will dive into a concise and neat way to perform conditional (if-else like) operations in your JavaScript code using the ternary operator.
What is a Ternary Operator?
A ternary operator is a shorthand method for writing a simple if-else statement.

It takes three operands, hence the name "ternary". The syntax is:
condition ? expression1 : expression2
Here's how it works:
- If the
conditionistrue,expression1is executed. - If the
conditionisfalse,expression2is executed.
Example
Consider the following scenario:
You want to determine if a number is even or odd.
Using traditional "if-else":
let number = 5;
let result;
if (number % 2 === 0) {
result = 'even';
} else {
result = 'odd';
}
console.log(result); // Outputs: odd
Using the ternary operator:
let number = 5; let result = (number % 2 === 0) ? 'even' : 'odd'; console.log(result); // Outputs: odd
See how much more concise that is?
Nested Ternaries
While you can nest ternary operators, be cautious, as it can make the code less readable.
Here's a simple example to show how it works:
let number = 0; let result = (number > 0) ? 'positive' : (number < 0) ? 'negative' : 'zero'; console.log(result); // Outputs: zero
Pro Tips 🤖
- Readability over brevity: While ternaries can shorten your code, don't sacrifice readability. If a condition gets too complex, it might be better to use the traditional
if-elseapproach. - Avoid deep nesting: As shown above, you can nest ternaries, but doing so excessively can make your code hard to understand. This again to do with readability. Remeber you write code for humans not machines. It usually gets minified anyway!
- Commenting: If you think a ternary might be confusing to others (or even future you), add a brief comment explaining its purpose.
Happy coding! 🦄
