• In Defense of the Ternary Statement
  • By Burke Holland
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: ZavierTang
  • Proofreader: Smilemuffie, Mnikn

A few months ago, I browsed a (now deleted) article on Hacker News about not using the if statement. If, like me, you’re not familiar with this idea, it’s worth checking it out. Just search Hacker News for “if statements” and you’ll see an article that says, “You probably don’t need if statements,” or that calls if statements “suspicious code,” or even “bad code.” Listen, you should know that different programming ideas are respectable, even if they claim to hurt others by using if.

If that’s not enough for you, there’s the anti-IF movement. If you join, you’ll see a nice banner on the site, and your name will be on it. Right! It would be so much fun if you did.

When I first came across this strange “anti-if” phenomenon, I thought it was funny, but it could just be some people going crazy online. You only have to Google to find people who are crazy about everything. Like this cat hater. KITTENS

After a while, I watched Linus Torvald’s TED talk. In that speech, he showed two slides. The first slide posted what he thought was the code for “Bad taste.”

The second is code for the same function, but in Linus’ eyes it is “good taste”.

I realize Linus is a bit of a polarizing character, and you might disagree with the description of “Good taste” versus “bad taste.” But I think, in general, the second slide is easier for beginners to understand. It is concise, has few logical branches, and contains no if statements. I want my code to look like this. It doesn’t have to be an advanced algorithm (it never will be), but I hope it is logically concise, remembering how Billy Corgan of the Smashing Pumpkins described it:

Cleanliness is godliness. And god is empty. Just like me.

  • Billy Corgan, “Zero”

How terrible! But it’s a great album.

In addition to making your code look cluttered, if statements or “branching logic” require your brain to simultaneously calculate two separate logical paths and all the things that might happen along those paths. If you also use nested if statements, the problem becomes even more complicated because your brain must jump around the tree like a drunken monkey as you generate and evaluate a decision tree. This greatly reduces the readability of the code. Remember, when writing code, you should think about which idiot will be maintaining it after you. Maybe, you.

As an idiot who has to maintain my own code, I’ve been consciously avoiding if statements in JavaScript lately. I didn’t always succeed, but I noticed that at the very least it forced me to think about problem-solving in a completely different way. It makes me a better developer because it makes me think, otherwise I’d be sitting on a beanbag eating peanuts and letting the if statement do all the work.

In avoiding writing if statements, I found that I liked the way the ternary and logical operators were used together in JavaScript. I’d like to suggest you now is not very popular ternary operator, you can use it with && and | | operators together to write some simple and readable code.

An undesirable ternary operator

When I first learned to program, people used to say, “Never use triadic operators.” They’re too complicated. So I didn’t use it. Not all the time. I’ve never used a ternary operator and I’ve never bothered to question whether those people are right.

But now, I don’t think so.

A ternary operator is just an if statement represented by a line of code. It is absolutely not true that they are too complex in any case. I mean, not that I want to be a maverick, but I can totally understand a simple ternary operator. Are we being a bit childish when we say we should avoid them forever? I think a well-formed ternary operator can beat an if statement.

Let’s take a simple example. Suppose we have an application in which we want to check the user’s login status. If we’re logged in, we jump to their home page. Otherwise, we will jump to the login page. Here is the standard if logic statement:

if (isLogggedIn) {
  navigateTo('profile');
}
else {
  navigateTo('unauthorized');
}
Copy the code

It’s pretty easy to get the job done with these six lines of code. Six lines. Remember, for every line of code you run, you have to remember the result of the above operation and how it affects the code below.

The following is the implementation code for the ternary operator:

isLoggedIn ? navigateTo('profile') : navigateTo('unauthorized');
Copy the code

Your brain only needs to compute this row, not six. You don’t have to move code up and down the line, and you don’t have to remember what came before.

However, one disadvantage of the ternary operators is that you cannot make logical decisions about just one case. Again, if you want to jump to the user’s home page while he is logged in, and do nothing if he is not logged in, the following code will not work:

/ /!!!!! Unable to compile!!
logggedIn ? navigateTo('profile')
Copy the code

You have to use the if statement here to get the job done. But is there another way?

You can use this technique in JavaScript when you want to process only one branch of a logical condition but don’t want to use an if statement. You can use the JavaScript in the | | (or) and && (and) operators work together to achieve this.

loggedIn && navigateTo('profile');
Copy the code

How is this achieved?

What we’re really saying here is: “Are both statements true?” If the first item is false, the JavaScript engine will not execute the second item. Since one of them is already false, we know that the result is not true. We take advantage of this mechanism: if the first item is false, JavaScript will not execute the second item. That is, “If the first item is true, execute the second item”.

What if I want to switch? What if we just want to navigate to the user’s home page without the user having logged in? You can use it directly in front of the loggedIn variable! But there is another way.

loggedIn || navigateTo('profile');
Copy the code

This code says, “Will either statement be true?” If the first term is false, you must evaluate the second term to be sure. If the first item is true, the second item is never executed because one of the items is already known to be true, so the result of the entire statement is true.

How about this?

if(! loggedIn) navigateTo('profile');
Copy the code

No, in this case, it’s not recommended. So, once you know you can use && and | | operators to implement the function of the if statement, you can use them to greatly simplify our code.

Here is a more complicated example. Suppose we have a login function that takes a User object as an argument. This object may be empty, so we need to check the Local storage to see if the user has saved the session locally. If yes, and he is an administrator, we will jump to the home page. Otherwise, we’ll navigate to another page that says the user is not authorized yet. The following is an implementation of a simple if statement.

function login(user) {
  if(! user) { user = getFromLocalStorage('user');
  }
  if (user) {
    if (user.loggedIn && user.isAdmin) {
      navigateTo('dashboard');
    }
    else {
      navigateTo('unauthorized'); }}else {
    navigateTo('unauthorized'); }}Copy the code

Oh. This can be complicated because we make a lot of conditional judgments about whether the User object is null or not. I don’t want my code to be too complicated, so let’s simplify it, because there’s a lot of redundant code here, and we need to encapsulate some functions.

function checkUser(user) {
  if(! user) { user = getFromLocalStorage('user');
  }
  return user;
}

function checkAdmin(user) {
  if (user.isLoggedIn && user.isAdmin) {
    navigateTo('dashboard');
  }
  else {
    navigateTo('unauthorized'); }}function login(user) {
  if (checkUser(user)) {
    checkAdmin(user);
  }
  else {
    navigateTo('unauthorized'); }}Copy the code

The login function is simpler, but there’s actually more code, and it’s not necessarily cleaner when you consider the whole code and not just the login function.

I suggest abandoning the if statement, using the ternary operator, and using the logical operator, so we can do all of this in two lines of code.

function login(user) {
  user = user || getFromLocalStorage('user');
  user && (user.loggedIn && user.isAdmin) ? navigateTo('dashboard') : navigateTo('unauthorized')}Copy the code

That’s it. All annoying if statement blocks have two lines folded. If the second line of code seems a bit long and cumbersome to read, wrap it so it’s on its own line.

function login(user) {
  user = user || getFromLocalStorage("user");
  user && (user.loggedIn && user.isAdmin)
    ? navigateTo("dashboard")
    : navigateTo("unauthorized");
}
Copy the code

If you are worried about other people may not know && and | | operators in JavaScript works, please add some comments and format your code.

function login(user) {
  // If user is empty, check local storage
  // Check whether the user object is saved
  user = user || getFromLocalStorage("user");
  
  // Make sure user is not empty, and
  // Is logged in and is the administrator. Otherwise, access is denied.
  user && (user.loggedIn && user.isAdmin)
    ? navigateTo("dashboard")
    : navigateTo("unauthorized");
}
Copy the code

other

Perhaps there are some other tricks you can use to handle JavaScript conditional judgments.

The assignment

One of my favorite techniques (used above) is a single line of code to determine if a variable is empty, and then reassign if it is. Using the | | operator to complete.

user = user || getFromLocalStorage('user');
Copy the code

You can go on and on:

user = user || getFromLocalStorage('user') | |await getFromDatabase('user') | |new User();
Copy the code

This also applies to ternary operators:

user = user ? getFromLocalStorage('user') : new User();
Copy the code

Combination conditions

You can provide multiple execution statements for ternary operators. For example, if we want to simultaneously log that the user has logged in and then jump to a page, we can do so without encapsulating all of this into another function. As follows, enclosed in parentheses and separated by commas.

isLoggedIn ? (log('Logged In'), navigateTo('dashboard')) : navigateTo('unauthorized');
Copy the code

This also applies to && and | | operators:

isLoggedIn && (log('Logged In'), navigateTo('dashboard'));
Copy the code

Nested ternary operators

You can nest ternary operators. Eric Elliot, in his article on ternary operators, illustrates this with the following example:

constwithTernary = ({ conditionA, conditionB }) => ( (! conditionA) ? valueC : (conditionB) ? valueA : valueB );Copy the code

One of the most interesting things Eric does here is to negate the first condition so that you don’t put question marks and colons together, which would be hard to read. I’m going to go one step further and add some indentation to the code. I also added braces and an explicit return statement, because parentheses would make me think I was calling a function when I wasn’t.

const withTernary = ({ conditionA, conditionB }) = > {
  return (
    (!conditionA)
      ? valueC  
      : (conditionB)
        ? valueA
        : valueB
  )
}
Copy the code

In general, you should not nest ternary operators or if statements. Any of the above Hacker News articles would shame you into coming to the same conclusion. While I’m not here to insult you, I’m just saying that if you stop overusing the if statement, maybe (just maybe) you’ll thank yourself later.


This is my view of the misunderstood ternary and logical operators. I think they can help you write clean, readable code and avoid if statements altogether. Now, like Linus Torvalds, we can end it all with “Good Taste.” I could retire early and live the rest of my life in peace.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.