Shorter If Statements With Ternary Operator π₯π
2020 Apr 21st
I want to start this article by specifying that code readability comes before concise syntax. The code should be explicit, so other developers understand what is happening. This is my opinion, though. I would not like to work with code that does ten things in one line.
However, there are times where we can write intelligible, and shorter code too. Why not take advantage of that? Remember this, though: never sacrifice code readability. Short, smart code is all fun and games until you have to come back to it and you do not have a clue of what it does.
Putting that aside, let’s see how we can make the code shorter with the ternary operator.
TERNARY OPERATOR π
The conditional (ternary) operator takes three operands:
- The condition, which is followed by a question mark (
?
) - An expression to execute if the condition is true
- A second expression to execute if the condition is false.
This translates into condition ? executeIfTRUE : executeIfFALSE
.
AN EXAMPLE
Let’s have a look at an if-else statement:
const checkAge = (age) => { if (age <= 10) { return 'You can only watch cartoons'; } else if (age <= 21) { return 'You can watch family and comedy movies'; } else { return 'You can watch any movies'; } };
In the above code snippet, we have nine lines of code for a simple check. Why not make that shorter? Let’s see how it
const checkAge = (age) => { return (age <= 10) ? 'You can only watch cartoons' : (age <= 21) ? 'You can watch family and comedy movies' : 'You can watch any movies'; };
What do you think about it? By the way, you can write it in one line. I split it into multiple lines for a better understanding.
Another example would be when you check if a name is empty. We could do that as follows:
person ? person.name : 'stranger';
However, these are just two examples. There are many more use cases where the conditional operator can be used.
CONCLUSION
That is all about the conditional (ternary) operator. It is excellent for simple use cases because it makes the code more concise. However, in some instances, it can make the code more complex and harder to understand.
You can read more about the conditional (ternary) operator on MDN.
Also, you can read the article I wrote yesterday about making promises better with async/await.
Donation β€οΈ
Support my work! β€οΈπ
Do you like my articles? Do you like my tweets? Do you like my work? β€οΈ
From now on you can support me by donating any amount you want! π
βto donate more than $1.00, replace digit 1 with how much you want to donate β$1.00