A dark walking path through white snow

if-else decisions are so common in coding languages that most have some sort of shortcut to create them. In JavaScript, this shortcut is referred to as a ternary, and is the only operator that uses two symbols.

The ternary operator is not merely a shortcut: it is an expression that returns a value, making it extremely powerful in the right hands.

“Ternary” means “composed of three parts” and refers to the three operands of the expression, separated by the two symbols of the operator:

condition ? expression1 : expression2

The condition is any expression that will evaluate to true or false. If true, the expression immediately after the ? will be executed; if false, the expression after the : will be run instead. The result of this expression often becomes the value of a variable.

Ternaries - also known as conditional operators - are often used where classical if else constructions would be awkward. Ternaries also have the advantage of being considerably more succinct:

var now = new Date(),
greeting = "Good" + ((now.getHours() >= 18) ? " evening." : " day.");

The above code will write “Good day” to the console unless it is after 6pm, in which case “Good evening” will be written instead.

Another, more complex example, from my JavaScript randomness recipes article:

function coinFlip() {
    return (Math.floor(Math.random() * 2) === 0) ? "up" : "down";

If the number provided by the expression on the left is 0, the word up is returned; otherwise, the word down is provided instead.

A Shorter Shortcut

The ternary operator must feature all three operands; a shortcut for if without an else, doesn’t formally exist. However, it is possible to structure something close by using an equality comparison operator, a logical AND operator and parentheses:

var highest,
chosenMountain = "Katmandu";
chosenMountain == "Everest" && (highest = true);

If chosenMountain is “Everest”, the highest variable will be set to true; otherwise, it will be false (the default).

Must You Use the Ternary Operator?

Just like other shortcuts in JavaScript, using the ternary operator is almost entirely optional: it works far better in many circumstances than if else, but it doesn’t have to replace it. In most cases, the same evaluation can be written either way in your code; the ternary operator is simply more efficient.

Photograph by Juhani, licensed under Creative Commons.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.