Ternary
The ternary operator is a shorthand method of writing conditional statements (if/else). The syntax for a ternary operator is:
(x > 0) ? y : z
In this example, the conditional statement is x > 0
. If the condition is true, then value y
will print to the console. If it is false, value z
will print instead. This is the same as:
While it is useful for condensing code, it can be difficult to read. Be careful when using it to ensure that the code does what you want it to.
Using multiple ternary operators
You can string together several ternary operator statements in place of if/else
statements, like so:
In this case, if x == 0 is true, the first option is returned, and hello is printed to the console. If it is false, it moves to the second option, which is another conditional. If x is less than 0, the first option "hi" is returned, whereas if x is greater than 0, the second option "goodbye" is returned instead. Ternary operators can be chanined together indefinetly, just as if/else statements can be repeated over and over for different conditions.
File Location
We will be working in the following file:
Practice
In
ternary.js
, re-write challenge #3 from the previous module using ternary operators."FizzBuzz" is a classic scripting challenge for many languages.
Several previous students have even been asked to solve this problem in technical interviews.
Write a program using conditional statements to print the following using the numbers 1-100:
If a number is divisible by 3, print Fizz
to the console. If a number is divisible by 5, print Buzz
to the console. If a number is divisible by 3 AND 5, print FizzBuzz
to the console. Otherwise, print the number to the console.
EXTRA CHALLENGE
Re-write the "FizzBuzz" program using ternary operators.
Last updated