Ternary operator

It’s well know that the ternary operator sintax is something like so:

(test) ? true doThis : false doThat

Suppose that in case condition is false we want do nothing. How to code “do nothing”? May I let it blank or there are an appropriate sintax?

yes :slight_smile:


(test) ? true doThis : ""

test && true doThis

You don’t need a ternary operator in this situation. Use an if() statement instead.

Many thanks to all for the reply
derfleurer & joebert
I need a ternary operator syntax.
RNEL
This works, but is this a syntactically correct solution under the JavaScript language view point? or is there a more elegant solution?

A ternary operator doesn’t have a do nothing option for either the true or false path since the entire ternary command returns a value and so both paths must set a value.

The “do nothing” value will depend on what value you want the ternary operator to return to indicate “do nothing”.

How about this?


if (test) {doThat}

The semicolon is optional. If you’re doing a one-liner with one statement, it can look cleaner without the semicolon.

You more commonly see it expanded out, such as:


if (test) {
    doThat;
}

Well, you could stick NULL in there, but it’s like putting pepper on a sugar cookie.

function f(a){alert(a);}
var y = true;
y ? f('y') : null;
!y ? null : f('!y');

If you actually do need a ternary, you’re leaving out something important from the information you’re giving us. Based on what you’ve told us, you do not need a ternary operator.

Sorry, my fault. The question is a theoretical one regarding the JavaScript syntax for ternary operator.
Now, in conclusion I think that the following syntaxes works but isn’t a good solution:

(test) ? doThis : "";
(test) ? doThis : null;

In this case the ternary operator isn’t the best solution and the syntax should be:

if (test) {
     doThis
} 

Or am I missing something? Any others thoughts?

There is difference of semantics in regards to ternary operators. It’s better when they are used to just to assign values.

If you want to run a different set of statements or functions, staying with the if/else structure is a better choice.

Yes, you are missing the first part of a statement containing a ternary operator.

The ternary operator works in a statement like this:

someVariable = (test) ? doThis : doThat;

and is the equivalent of:

if (test)
   someVariable = doThis;
else
   someVariable = doThat;

It is to simplify the assignment of a value to someVariable that you use a ternary operator and so there is no “do nothing” case since the purpose of a ternary operator is to select which of two values to assign. If you only have one value to assign then it simplifies to

someVariable = doThis;