Skip to content

Ternary

Like most languages, Javascript has a ternary operator.

It allows a value to be returned based on a condition. The basic anatomy of the ternary is:

condition ? valueIfTrue : valueIfFalse

Why?

A common pattern in programming is the following. We want to set the value of a variable to one thing if a condition is true, or another thing if it’s false:

let value = 0;
if (someCondition) {
value = 10
} else {
value = 20
}

You can see that the variable name value gets repeated three times (and we don’t want to repeat ourselves) as well as the assignment to the variable (=).

With the ternary operator, these six lines of code can instead be expressed as:

const value = someCondition ? 10 : 20;

Advanced

Of course we don’t have to use fixed values, we could be using functions as the condition, true and false values, or some combination thereof.

// Returns _true_ if it's past noon
const isAfternoon = () => new Date().getHours() > 12
// siesta() and fiesta() functions omitted...
const value = isAfternoon() ? seista() : fiesta();

Ternary operators can be nested. This is where they can start being unwieldy, hard to read. See if you can follow the logic of this ternary statement that nests four levels deep!

const hour = new Date().getHours();
const value = hour < 12 ?
(hour < 10 ? `morning` : `mid-morning`) :
(hour < 13 ? `lunchtime` :
(hour < 17 ? `afternoon` : `evening`)
)