A few things about the conditional operator:
- It is a ternary operator (not unary or binary) meaning it works with three values
- It’s written using a question mark (?) and then a colon (:)
- The value to the left of the question mark returns a boolean concept of true or false.
How does the conditional operator work?
The conditional operator uses three different values and looks something like this:
console.log(true ? "john is the winner" : "tracy is the winner");
//john is the winner
As you can see the value to the left of the question mark determines which of the in front of it is selected.
The rule here is if the value to the left of the question mark is true, then the value to the left of the colon is selected as the output. If the value to the left of the question mark is false, then the value to the right of the question mark is chosen.
Example 1: How conditional operators work
Let’s try an exercise.
Go ahead and tell me what the output here is.
console.log(-123 ? "first" : "second");
The answer is:
first
Why?
Because remember! In boolean, any number (positive or negative) is considered true while a 0 is considered false.
Here, we have -123 which is a number that’s negative. But that doesn’t matter because only 0 is false.
In turn, -123 is considered true and so according to the rules of the conditional operator, the output ends up being the value directly to the left of the colon!