Learn to Code via Tutorials on Repl.it

← Back to all posts
Ternaries

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.

Evanlicious (68)

This is very interesting, thank you for helping shorten my future code.

LiamDonohue (69)
``Console.WriteLine(null);``
SixBeeps (1059)

@LiamDonohue You have your logic swapped, and the C# version is identical to the Java version.

LiamDonohue (69)

lol

Struggling to figure out why strings are char pointers in C++

MatthewDoan1 (256)
``return Math.abs(n);``

Cool. Javascript has something similar :P

CodeABC123 (92)

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

Evanlicious (68)

@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.")``````
CodeABC123 (92)

No, I never said I need help! @Evanlicious

Evanlicious (68)

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

CodeABC123 (92)

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