JavaScript ternary operator
The ternary operator in JavaScript is a shorthand way to perform a conditional operation. It provides a concise way to write simple if...else
statements in a single line. The ternary operator takes three operands, which is why it is called "ternary."
Syntax
The syntax of the ternary operator is:
condition ? expressionIfTrue : expressionIfFalse;
How It Works
- Condition Evaluation: The
condition
is evaluated first. - True Expression: If the
condition
is true,expressionIfTrue
is evaluated and returned. - False Expression: If the
condition
is false,expressionIfFalse
is evaluated and returned.
Example
let age = 18;
let canVote = age >= 18 ? 'Yes' : 'No';
console.log(canVote); // 'Yes'
- Explanation:
- The
condition
isage >= 18
. - Since
age
is 18, the condition is true, so'Yes'
is assigned tocanVote
. - If
age
were less than 18,'No'
would be assigned tocanVote
.
- The
Key Points
Simple Conditional Expression: The ternary operator is ideal for simple conditions and expressions where you want to make the code more concise.
let number = 10; let result = number % 2 === 0 ? 'Even' : 'Odd'; console.log(result); // 'Even'
Nesting: You can nest ternary operators to handle multiple conditions, but it can reduce code readability if overused.
let score = 85; let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'D'; console.log(grade); // 'B'
- Explanation:
- This example uses nested ternary operators to determine the grade based on the score.
- Explanation:
Readability: While the ternary operator can make the code more concise, it can also make it harder to read if used with complex expressions or nested ternary operators. In such cases, using
if...else
statements may be more readable.let age = 22; let message = age >= 18 ? (age < 21 ? 'Young Adult' : 'Adult') : 'Minor'; console.log(message); // 'Adult'
- Explanation:
- This example uses a nested ternary operator to determine if the person is a 'Minor', 'Young Adult', or 'Adult' based on their age.
- Explanation:
Assignment: The ternary operator is often used in assignments to set values based on a condition.
let isMember = true; let discount = isMember ? 0.1 : 0.05; console.log(discount); // 0.1
- Explanation:
- The
discount
is set to0.1
ifisMember
is true; otherwise, it is set to0.05
.
- The
- Explanation:
Summary
- Syntax:
condition ? expressionIfTrue : expressionIfFalse;
- Usage: Provides a concise way to handle simple conditional logic.
- Nesting: Can be nested for more complex conditions but may impact readability.
- Readability: Best used for straightforward conditions; for complex logic,
if...else
might be clearer.