JavaScript conditional (ternary) operator
The conditional (ternary) operator in JavaScript is a concise way to perform conditional logic. It’s a shorthand for an if-else
statement and is often used to assign values based on a condition. The syntax is as follows:
condition ? expr1 : expr2
Breakdown:
condition
: A boolean expression that evaluates totrue
orfalse
.expr1
: The expression that is evaluated and returned if the condition istrue
.expr2
: The expression that is evaluated and returned if the condition isfalse
.
How It Works:
- If the
condition
istrue
,expr1
is returned. - If the
condition
isfalse
,expr2
is returned.
Examples:
Basic Example:
let age = 18; let canVote = age >= 18 ? 'Yes' : 'No'; console.log(canVote); // 'Yes'
In this example,
age >= 18
is the condition. Since it evaluates totrue
, the result of the ternary operator is'Yes'
.Nested Ternary Operator:
let score = 85; let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : score >= 70 ? 'C' : 'D'; console.log(grade); // 'B'
Here, the ternary operator is nested to handle multiple conditions. It checks the score range and assigns the corresponding grade.
Ternary Operator in Function Return:
function getDiscount(isMember) { return isMember ? 0.1 : 0.05; } console.log(getDiscount(true)); // 0.1 console.log(getDiscount(false)); // 0.05
The ternary operator returns a discount rate based on whether
isMember
istrue
orfalse
.Using Ternary Operator for Inline Styling:
let isDarkMode = true; let backgroundColor = isDarkMode ? 'black' : 'white'; console.log(backgroundColor); // 'black'
Here,
backgroundColor
is set based on theisDarkMode
boolean value.
Key Points:
- Readability: While ternary operators are useful for concise conditional expressions, overusing or nesting them can make code harder to read. For more complex conditions, traditional
if-else
statements might be clearer. - Assignment: Ternary operators are commonly used to assign values based on conditions, which can make code more concise compared to using multiple
if-else
statements.