The JavaScript Conditional Operator (commonly known as the Ternary Operator) is a concise way to perform conditional operations. It is the only operator in JavaScript that takes three operands.
Syntax:
condition ? expression1 : expression2;
- condition: A boolean expression that is evaluated.
- expression1: The value returned if the condition is
true
. - expression2: The value returned if the condition is
false
.
Basic Example:
let age = 18; let message = age >= 18 ? "You are an adult." : "You are a minor."; console.log(message); // "You are an adult."
Explanation:
- If
age >= 18
evaluates totrue
,message
is assigned"You are an adult."
. - If
age >= 18
evaluates tofalse
,message
is assigned"You are a minor."
.
Example with Functions:
let canDrive = (age) => age >= 16 ? "Yes" : "No"; console.log(canDrive(18)); // "Yes" console.log(canDrive(15)); // "No"
Nested Ternary Operators:
Ternary operators can be nested, but this can make the code less readable.
Example:
let score = 85; let grade = score > 90 ? "A" : score > 80 ? "B" : score > 70 ? "C" : "F"; console.log(grade); // "B"
Best Practices:
- Use the ternary operator for simple, concise conditions.
- Avoid overusing or nesting ternary operators, as this can make the code hard to read and maintain.
- For more complex conditions, consider using an
if-else
statement for clarity.
Comparison with if-else
:
Using if-else
:
let age = 20; let message; if (age >= 18) { message = "You are an adult."; } else { message = "You are a minor."; } console.log(message); // "You are an adult."
Using Ternary Operator:
let age = 20; let message = age >= 18 ? "You are an adult." : "You are a minor."; console.log(message); // "You are an adult."
Summary:
- The ternary operator is a shorthand for
if-else
statements. - It provides a compact way to write simple conditional expressions.
- Use it when you need a quick, inline decision between two values.