if else statements. The main reason for using ternary operators is they can be written on a single line and remain readable, making the program cleaner.
Ternary IF-ELSE Statement
A ternary operator is initiated with a
? (question mark) after a comparison statement. After the question mark is the result to return if the comparison is
true, followed by a
: (colon) containing the result to return if the comparison is
var value = 1 < 2 ? true : false; console.log(value);
Ternary ELSE IF Statement
It is possible to perform ternary
else if statements by putting a new comparison in
() (parenthesis) in the else (
:) part of the previous ternary statement.
var value = 2 < 1 ? true : (2 > 1 ? true : false); console.log(value);
The first comparison is
false so the second comparison is checked and
true is returned.
You can, in theory, nest as many ternary
else if statements as you wish, though as one can imagine this would get complex and hard to maintain very quickly.
Using Ternary Operators Without Comparisons
Ternary operators can be supplied with a
false value from a variable.
var result = true; var text = result ? 'approved' : 'denied'; console.log(text);
You now know how to use ternary operators in JavsScript. The key point to remember is that ternary operators should be used where appropriate because in many cases regular
if else if logic can be much easier to read and maintain.