JavaScript ternary operator without else condition | Is it possible?

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:

Although it’s safer to have braces if you need to add more than one statement in the future:

HTML example code:-


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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.