# 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:

```javascript
if (x > 0) {
    return y;
} else {
    return z;
}
```

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:

```javascript
//Conditional statements
if (x == 0) {
    console.log("hello");
} else if (x < 0) {
    console.log("hi");
} else if {
    console.log("goodbye");
}

//Ternary operators

console.log((x == 0) ? "hello" : (x < 0) ? "hi" : "goodbye");
```

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:

```
    javascript-library
        └── 0-PreWork
        └── 1-Fundamentals
            └── 1-Grammar-and-Types
            └── 2-ControlFlow-and-ErrorHandling
            └── 3-Loops
            └── 4-Functions
            └── 5-Expressions-and-Operators
                01-assignment.js 
                02-comparision.js 
                03-ternary.js <----You will be working in this file.
```

## Practice

1. In `ternary.js`, re-write challenge #3 from the previous module using ternary operators.
2. "FizzBuzz" is a classic scripting challenge for many languages.&#x20;
3. Several previous students have even been asked to solve this problem in technical interviews.&#x20;
4. 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.
