In this tutorial, I will explain how I learned this, and hopefully it teaches you something new.
I have a video version on this topic you can watch as well to supplement your learning.
How I Learned About the Ternary Operator
"The ternary operator is a conditional operator..."
Here's a screenshot of that sentence:
Note: I'm going to make some updates to that article when I'm done with this, so don't be surprised if you do not see some of the text I mention here.
After publishing that article, someone shared it on Twitter, saying "Thanks", and then someone else made a comment under the tweet explaining that "A ternary operator is a conditional operator" is a wrong statement:
These comments made me take a step back, and after reading it a few times, it made total sense. Thanks, Jon!
I then went online to research ternary operators, and the categories of operators in general (which also include unary and binary) operators.
It's True – a Ternary Operator is not a Conditional Operator
In my article on Unary, Binary, and Ternary Operators, I explained that:
- Unary operators require one operand
- Binary operators require two operands
- Ternary operators require three operands
An example of a unary operator is
typeof, which requires only one operand.
For binary operators, an example is the arithmetic plus
+ operator which requires two operands (one before, and the other after the operand) to perform the sum operation.
While unary and binary operators have a couple of examples under them, there is ONLY ONE operator which classifies as a ternary operator: the conditional operator. This is where the confusion comes from.
The conditional operator requires three operands:
condition ? truthyExpression : falsyExpression
condition is the first operand,
truthyExpression is the second, and
falsyExpression is the third.
But one thing to note here is that in some other programming languages (that currently exist or will in the future), there could be more examples of the ternary operator.
So the point is that "a ternary operator is not a conditional operator". The better statement is: "A conditional operator is a ternary operator". A conditional operator requires three operands, which means it falls under the ternary category.
The purpose of this article isn't to say "don't ever say a ternary operator is a conditional operator". You can still stay that and every developer will likely understand what you're saying.
The purpose of this article is to show you that "literally", that statement is not correct, even though it is widely used.
If you learned something from this article, please share it with others :)