Ternary Operators

While we’re on the topic of operators, we might as well throw in the ternary operator. As you might have guessed, the ternary operator has three operands. Not all languages have ternary operators because a ternary is really just a more concise way of writing a simple if/else statement (see else if section). The syntax for a ternary is operandA ? operandB : operandC. If operandA is true, then evaluate operandB; otherwise, evaluate operandC. Let’s see it in action in Listing 7.8.

Listing 7.8 Ternary Fun

// Ask for a numbervar favoriteNumber = prompt('What\'s your favorite number?');// Turn the string into a number.favoriteNumber = parseInt(favoriteNumber, 10);var oddOrEven = ( (favoriteNumber % 2 ...

Get Learning to Program now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.