What is the Conditional Operator? The Conditional Operator is sometimes called the Ternary...
The Conditional Operator is sometimes called the Ternary Operator or "question mark" operator. It is an operator that allows us to write theif ... else
statement in a short and concise way. The operator is used with a question mark?
hence the name "question mark" operator. The operator has three operands hence the name "ternary" operator.
Normally, you would write anif ... else
statement the following way:
let value;
if (condition) {
value = "true";
} else {
value = "false";
}
With the Conditional operator, you can write the above code the following way:
// syntax -> condition ? operand2: operand3;
let value = condition ? "true" : "false";
The first operand is the condition you want to evaluate, followed by a question mark (?
). The second operand is the expression you wish to execute if the condition is "truthy" , followed by a colon (:
). And lastly, the third operand is the expression to execute if the condition is "falsy" .
You can see that with the Conditional operator, you can neatly write anif ... else
statement block into one line and assign it directly to a variable.
The Conditional operator is often used as an alternative toif ... else
statement block because it is shorter to write, sometimes it is still better for code readability to useif ... else
statements. That being said, you can use Conditional operator forif ... else if ... else
statements as well.
For example:
function getAgeGroup(age) {
if (age >= 18) {
return "adult";
}
else if (age >= 13) {
return "adolescent";
}
else {
return "child";
}
}
Here we have a function that return the age terminology based on the parameter "age", the function evaluate the input argument withif ... else if ... else
statement and return appropriate term.
function getAgeGroup(age) {
return age >= 18 ? "adult"
: age >= 13 ? "adolescent"
: "child";
}
You can see that it much shorter, as for whether it is as readable, I will let you be the judge of that ????.
(Explanation: In the example, if the first condition is "truthy" it will return the string "adult", otherwise, it will move to the second condition and again check for "truthy" and return the string "adolescent". If the second condition is "falsy" then the string "child" will be returned.)
The Conditional Operator has three operands and can be used as an alternative toif ... else
statement block. Itcanbe difficult to read so it should be used for simple cases. An example of my use case would be in React, where you can't useif
condition directly inside the JSX so you could use this conditional operator for conditional rendering.
Thank you for reading, please leave a comment if you found it helpful, or feedback if you found a mistake or would like to add to it.