Ternary operator
The ?: operator, or the ternary operator, is a shorthand form of the if...else conditional.
It lets you write the condition, the check, and both result options in a single line.
Syntax
condition ? expression_if_true : expression_if_falseHow it works
- First, the
conditionis evaluated. - If it is truthy (
true), the first expression is returned. - If it is falsy (
false), the second expression is returned.
Example
const age = 20;
const message = age >= 18
? 'Access granted'
: 'Access denied';
console.log(message); // "Access granted"Here,
age >= 18is the condition. Since it is true, the first part is returned ('Access granted').
The same thing with if...else
let message;
if (age >= 18) {
message = 'Access granted';
} else {
message = 'Access denied';
}The
?:operator is simply a compact way of writingif...else.
Example with a function
function checkAccess(role) {
return role === 'admin'
? 'Full access'
: 'Limited access';
}
console.log(checkAccess('admin')); // "Full access"The ternary operator returns a value
Unlike if, the ternary operator is an expression,
not just a statement.
That means it can be used directly in an assignment,
in function arguments, and so on:
console.log(5 > 3 ? 'Yes' : 'No'); // "Yes"Nested ternary operators (be careful!)
Sometimes you'll come across nested ternary expressions:
const age = 25;
const category = age < 13
? 'child'
: age < 20
? 'teenager'
: 'adult';
console.log(category); // "adult"It works correctly, but hurts readability, so for complex conditions it's better to use a regular
if...else.
Example with logic in expressions
const user = { name: 'Tim', premium: true };
const label = user.premium ? 'Premium' : 'Standard';
console.log(label); // "Premium"Combination with && and ||
The ternary is often used together with other logical operators:
const access = user && user.isAdmin ? 'OK' : 'DENIED';Summary
| Part | What it does |
|---|---|
condition | Checked for true/false |
? expression1 | Runs if the condition is true |
: expression2 | Runs if the condition is false |
Ternary operator examples
let score = 75;
let result = score >= 60 ? 'Passed' : 'Failed';
console.log(result); // "Passed"
let color = (score > 90) ? 'green' : (score > 70) ? 'orange' : 'red';
console.log(color); // "orange"In short
| Notation | Meaning |
|---|---|
a ? b : c | If a is true → return b, otherwise → c |
| Returns | The result of the selected expression |
| Can be used in | Assignments, functions, templates, JSX, etc. |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.