The ternary operator.
When I first bought my JavaScript book (JavaScript: The Definitive Guide by David Flanagan), I read like the first ten chapters of it at once. At one point, I read about something called the ternary operator, given by ?:
. At the time I didn’t understand exactly what its use was, but I’ve since seen it again and decided to look into it.
In mathematics, a ternary operator is any function that takes in three inputs and outputs one result. An example is distributivity of addition and multiplication:
\[f(x,y,z) = (x+y)z = xz + yz\]is an example that takes in three inputs (numbers $x$, $y$, and $z$) and returns one output (the number $xz+yz$).
In computer languages, the ternary operator generally refers to one thing, the if-else statement. In fact, and this wasn’t clear in my JavaScript book when I was reading about it, the ternary operator is just shorthand notation for an if-else statement. In other words, the ternary operator condenses the statement
if (a === 4) {
b = b + 1;
} else {
a = a + 1;
}
which adds 1 to b
if a
is equal to 4 and adds 1 to a
otherwise, to:
a === 4 ? b = b + 1 : a = a + 1
I read about this when I was browsing the internet about “idiomatic Python”. In Python, there is no ternary operator, but the site I went to says the idiomatic way to make a ternary operator in Python is to take a statement like:
a = True
value = 0
if a:
value = 1
print(value)
and replace it with:
a = True
value = 1 if a else 0
print(value)
(In JavaScript this statement would be a = True; a === True ? value = 1 : value = 0; console.log(value)
.)
Wikipedia describes the ternary operator in mathematics, as well as its incarnation in various programming languages. One example I’m familiar with is in SQL – the CASE
command is actually a generalization of the ternary operator. It is not a ternary operator but a $(2n+1)$-ary operator, in that it takes an odd number of inputs and returns one output:
SELECT (CASE WHEN a > b THEN x WHEN a < b THEN y ELSE z END)
AS CONDITIONAL_EXAMPLE
FROM tab;
In pseudocode, the expression in the parentheses is “if a > b then x else if a < b then y else z”, or, in JavaScript, a > b ? x : a < b ? y : z
. So in this case it’s a $5$-ary operator!
I seem to remember reading about this in the context of idiomatic JavaScript in my book, but it was hard to find where I read about it. Nice that I looked this up, though, and now I understand it.