What is it and what does it solve.
The ternary operator a.k.a the conditional operator is a simple and cleaner approach instead of if … else statements. It can be used in many scenarios which includes variable assignment or conditional execution. We will be discussing further on this below.
Comparison.
// Traditional approach
if (condition) {
returnExpressionIfTrue ;
}
else {
returnExpressionIfFalse
}
// Ternary operator
(condition) ? returnExpressionIfTrue : returnExpressionIfFalse;
Above code shows how easy it is to use the ternary operator and how feasible it is to understand and cleaner.
Over here the first block in the if statement is executed when the condition is true and if it is a falsy value the express in the else is executed. (After the colon)
Use cases of the ternary operator
- Executing expressions based on conditions
- Falsy value checks (Null or undefined)
- Assign values based on a condition
Executing expressions based on conditions
- Operations can be easily conditionally executed with the use of this operator. This will drastically minimise lines of code.
// Ternary operator used to return function based on condition
const run = () => {
const hungry = true;
return hungry ? eat() : workout()
}
// The eat section will be executed as the condition is valid
Null or undefined value checks
- Another common instance where the ternary operator can be used is setting a default value if a variable/object is empty.
// Lets create a sample user object
const user = { name: 'Taylor Swift' };
// Assume you want to print the age of the above
console.log(user.age); // Returns undefined
// Using the ternary operator we can set a default value
console.log(user.age ? user.age : 20);
// 20 will be output as age is undefined
Assign values based on a condition
- There maybe instances where we need to assign some value to a variable based on a specific condition. The traditional approach would be to simply use an if else statement but the ternary operator makes it much simpler.
let response;
let message;
// lets assume that the response is a success
response = 'SUCCESS';
message = response === SUCCESS ? 'Response received' : 'Error in response';
An instance where ternary operator is not the preferred choice
Using nested ternaries
A nested ternary simply takes the place of another ternary operator within itself which is used to evaluate several conditions. Think of an example of a condition with several else if statements.
const mark = 65;
let grade =
mark >= 80 ? 'A' : mark >= 70 ? 'B' : mark >= 60 ? 'C' : mark >= 40
? 'D' : 'F';
The code block above shows the ternary operator used instead of several else if statements. Someone that is very familiar with the ternary operator could be able to figure this out but its very difficult to understand and will take a lot of time in figuring this out. For an instance like this the switch case is more preferred or even the else if blocks.
Conclusion
The ternary operator will make life very feasible for any developer as it is shorter than traditional if … else statements and easier to understand for someone that is reading the code. However do keep in mind there might be still instances where the if … else or switch case statements are preferred.