JavaScript ternary operator is frequently used as a shortcut for the if statement. It’s a one-line shorthand for an if-else statement and also called the conditional operator in JavaScript.
The ternary operator is the only JavaScript operator that takes three operands. First condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
Syntax
1 |
<var>condition</var> ? <var>exprIfTrue</var> : <var>exprIfFalse</var> |
Parameters values
condition
:expression whose value is used as a condition.
exprIfTrue
: Value or expression on true condition.exprIfFalse
: Value or expression on false condition.
Example of JavaScript ternary operator
Let’s see the example of how to use the ternary operator as the shortcut for the if-else statement in JavaScript
1 2 3 4 5 6 7 8 9 10 |
<html> <head> <title>Sample Code</title> <script type="text/javascript"> var age = 19; var canDrive = age > 16 ? 'YES' : 'No'; alert(canDrive) </script> </head> </html> |
Output:

Ternary operator multiple conditions JavaScript
The ternary operator seems more appropriate since you have fewer conditions, although an if
would be much easier to read on Multiple conditions.
If-else statement for multiple conditions
1 2 3 4 5 6 7 8 |
String year = "senior"; if (credits < 30) { year = "freshman"; } else if (credits <= 59) { year = "sophomore"; } else if (credits <= 89) { year = "junior"; } |
Contrast this with the ternary operator:
1 |
String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior"; |
Nested ternary operator JavaScript
You must search first What is an Alternative to the nested ternary operator in JS? Because the nested ternary operator is a very complicated expression.
Here are alternatives:-
- That
if
/else
you don’t want to do - A
switch
combined withif
/else
JavaScript ternary shorthand
use ||
. Unlike PHP, JavaScript’s ||
operator will return the first non-falsy value, not a normalized Boolean.
1 |
foo || 'world' |
Ternary operator without else in JavaScript
First of all, a ternary expression is not a replacement for an if/else construct – it’s an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.
Code for without else:-
1 |
var x = condition || null; |
Do comment if you have doubts and suggestion on this topic.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version