Skip to content

JavaScript ternary operator without else condition | Is it possible?

  • by

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:

if(condition) x = true;

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

if(condition) { x = true; }

HTML example code:-




  

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: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading