JAVASCRIPT TERNARY OPERATORS
Using ternary operators is the best way to write short and precise code when using if/else statements. In short, it is used to avoid writing lengthy code when using these conditionals.
Ternary operators execute the exact same purpose of the conditional, with just a shorter and more concise structure.
conditional ? (if condition is true) : (if condition is false)
example 1
For example, examine the following code…
output: yellow
To use the ternary operator, first provide a conditional statement on the left side of the ?
. Then, between the ?
and :
write the code that would run if the condition is true
and on the right-hand side of the :
write the code that would run if the condition is false
. For example, you can rewrite the example code above as:
output = yellow
This code not only replaces the conditional but also handles the variable assignment for color
.
example 2
output = herbivore;
The code can be simplified by the ternary series below:
output = herbivore;