How to Use Ternary Operators in JavaScript
Ternary operators in JavaScript are used to make conditional statements and work like regular 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.
In this tutorial, we will learn how to use ternary operators in JavaScript so you can apply them where appropriate.
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 false
.
var value = 1 < 2 ? true : false;
console.log(value);
true
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);
true
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 true
or false
value from a variable.
var result = true;
var text = result ? 'approved' : 'denied';
console.log(text);
approved
Conclusion
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.