Question

Anyone have a good trick to remember the standard ternary syntax?

Specifically whether the '?' or ':' comes first. I have consistently gotten this backwards over the years.

Was it helpful?

Solution

The condition you are checking is kind of like a question, so the question mark comes first.

x > 0 ? 1 : 0

Think of this statement as three English sentences: "Is x greater than 0? Then 1. Else, 0." You have one sentence for each clause in the statement.

The predicate:

x > 0 ? /* Is x greater than 0? */

The "true" branch:

1 /* Then 1. */

The "false" branch:

: 0 /* Else, 0. */

OTHER TIPS

As far as remembering which symbol comes first, I just think of the fact that the first part is a question, "Is it true or not?", so the question mark goes first.

I think of the syntax in this manner

Question ? Yes : No

in python I read it as a normal English sentence:

 a equals b if condition is true else c

Think of it this way: a ternary statement consists of three parts: the question, the code to execute if the answer to the question is "yes" and the code if the answer is "no". The "?" comes after the question like it does in English sentences.

"?" is a question mark so it means "if".

A colon means, "now it comes", "then do".

The good thing about the ternary operator is that you are not forced to use it, especially if you are having problems remembering the syntax. Just use an if-statement which is more readable most times.

And no - the ternary has no better performace then an if-statement.

It goes like this:

myVariable = this.testMethod() ? 'value for true case' : 'value for false case'

If you're unit tests still pass when you get it wrong, then either it doesn't matter or your tests aren't covering enough of the paths through the code. If there's too long a gap between typing it and getting a pass/fail from the tests, that's another issue. Very few little syntax nits matter in the presence of good, fast tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top