catalins.tech with Gatsby

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:

  1. The condition, which is followed by a question mark (?)
  2. An expression to execute if the condition is true
  3. 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