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
: 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:
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:
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.