Let’s simplify if statement with the Ternary Operator in JavaScript

I want to begin this topic by specifying that code readability comes before concise syntax. The code should be explicit, so other developers understand what’s happening. This can be my opinion, though. I’d not wish to work with code that does tons of things in one line.
However, there are times where we are able to write shorter, and intelligible code too. Why not profit from that? Remember this, though: never sacrifice code readability. Short, smart code is all fun and games until you have got to return back thereto and you are doing not have a clue of what it does. Putting this aside, let’s see how Ternary Operator simplifies if Statement.
The ternary operator takes 3 parameters:
condition ? value if true : value if false- The condition, followed by “ ? ” is the actual testing to be performed. The output of the condition will be either true or false or at least coerce to either boolean value.
- The expression between “ ? ” and “ : ” is to be executed if the condition returns true.
- And finally, the expression after “ : ” is to be executed if the condition returns false.
Let’s make it clear with an example.
const whatToWatch = (age) => {
if (age <= 12) {
return "You can onle watch Tom & Jerry";
} else if (age <= 20){
return "You can watch FRIENDS";
} else {
return "You can watch Game of Thrones"
}
};The above lines of code consist of multiple if, else-if statement. Let’s shorten this with the ternary operator.
const whatToWatch = (age) => {
return (age <= 12) ?
"You can only watch Tom & Jerry" :
(age <= 20) ?
"You can watch FRIENDS" :
"You can watch Game of Thrones"
};It’s quite simplified now. But we can do more writing the above lines of code in one line.
const whatToWatch = (age) => {
return (age <= 12) ? "You can only watch Tom & Jerry" : (age <= 20) ?"You can watch FRIENDS" : "You can watch Game of Thrones"
};Conclusion
It’s all about the ternary operator. It makes the if-statement shorter and is very helpful in simple use cases. However, in some cases, the use of the ternary operator may make the code complex to understand. To learn more you can visit the documentation by MDN.