What is the ternary operator and how is it used?
TL;DR
The ternary operator is a shorthand for an if-else
statement in JavaScript. It takes three operands: a condition, a result for true, and a result for false. The syntax is condition ? expr1 : expr2
. For example, let result = (a > b) ? 'a is greater' : 'b is greater';
assigns 'a is greater'
to result
if a
is greater than b
, otherwise it assigns 'b is greater'
.
What is the ternary operator and how is it used?
Introduction
The ternary operator, also known as the conditional operator, is a concise way to perform conditional evaluations in JavaScript. It is the only operator in JavaScript that takes three operands.
Syntax
The syntax for the ternary operator is:
condition ? expr1 : expr2;
condition
: An expression that evaluates totrue
orfalse
expr1
: An expression that is executed if the condition istrue
expr2
: An expression that is executed if the condition isfalse
Example usage
Here is a basic example of the ternary operator:
let age = 18;let canVote = age >= 18 ? 'Yes' : 'No';console.log(canVote); // Output: Yes
In this example, the condition age >= 18
is evaluated. If it is true
, the string 'Yes'
is assigned to canVote
. If it is false
, the string 'No'
is assigned to canVote
.
Nested ternary operators
You can also nest ternary operators, although it can make the code harder to read:
let score = 85;let grade =score >= 90? 'A': score >= 80? 'B': score >= 70? 'C': score >= 60? 'D': 'F';console.log(grade); // Output: B
In this example, the ternary operator is used to assign a grade based on the value of score
.
Use cases
- Simple conditional assignments: When you need to assign a value based on a condition.
- Inline conditional rendering: Useful in JSX for conditional rendering in React.
Best practices
- Readability: While the ternary operator can make code more concise, overusing it or nesting it too deeply can make the code hard to read. Use it judiciously.
- Complex conditions: For complex conditions, consider using
if-else
statements for better readability.