Ternaries
h
SixBeeps (2891)

One of the simplest concepts in programming is the if-else statement.

if (someCondition) {
   doAThing();
} else {
   doAnotherThing();
}

Of course, if and if-else statements have a variety of different purposes. But, arguably the most common usage is for assignment of some variable or calculating something. For example, let's look and an absolute value function (this is written in Java, but this tutorial can apply to most languages)

int abs(int n) {
    if (n < 0) {
        return -n;
    } else {
        return n;
    }
}

This is fine and all, but we can shorten it a bit using something called a ternary.

A ternary is one of the few (if not the only) logic operator that takes 3 operands. The first value is some boolean expression, like score>75 or word=="yeet". The second and third are your values. The ternary will evaluate to the second if your boolean expression is true, and the third if it is false. The syntax varies from language to language, but a common way to write one of these is a ? b : c where a is your boolean expression, and b and c are your second and third values.

Let's re-write the abs() function above using ternaries:

int abs(int n) {
    return n<0 ? -n : n;
}

Nice and concise. For a list of how to use ternary expressions in various languages, refer to here.

You are viewing a single comment. View All
[deleted]

If else is not the simplest. I’ve been coding for almost a year and if else is still a tiny bit confusing.

Evanlicious (76)

@CodeABC123 Think about it like this: Let's say there are seven children on the swings. The limit, however, is six or less. If there are more than six children, one must go away. Otherwise (else), leave the children be.

Python Code:

children = 7

if children > 6:
  extra = children - 6
  children = children - extra
  print("There are now six children on the swings.")

else:
  print("There was already six children on the swings.")
[deleted]

No, I never said I need help! @Evanlicious

Evanlicious (76)

@CodeABC123 Oh, okay! Sorry about that. Just wanted to see if it did anything to help.

[deleted]

It’s fine. We all misunderstand sometimes. @Evanlicious