How to use a ternary operator in JavaScript without else or empty? Is it possible?
A ternary operation is called ternary because it takes 3 arguments, if it takes 2 it is a binary operation.
It’s an expression returning a value. If you omit the else you would have an undefined situation where the expression would not return a value.
You can use an if statement.
The option of JavaScript ternary operator without else
You can do this:
1 |
if(condition) x = true; |
Although it’s safer to have braces if you need to add more than one statement in the future:
1 |
if(condition) { x = true; } |
HTML example code:-
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <body> <script type="text/javascript"> var a = 1; if(a == 1) { x = true; } alert(x); </script> </body> </html> |
Output:

Note: 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.
Do comment if you have any doubts and suggestion on this topic.
Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version