Ternary
Like most languages, Javascript has a ternary operator.
It allows a value to be returned based on a condition. The basic anatomy of the ternary is:
Why?
A common pattern in programming is the following. We want to set the value of a variable to one thing if a condition is true, or another thing if it’s false:
You can see that the variable name value
gets repeated three times (and we don’t want to repeat ourselves) as well as the assignment to the variable (=
).
With the ternary operator, these six lines of code can instead be expressed as:
Advanced
Of course we don’t have to use fixed values, we could be using functions as the condition, true and false values, or some combination thereof.
Ternary operators can be nested. This is where they can start being unwieldy, hard to read. See if you can follow the logic of this ternary statement that nests four levels deep!