How Does the Ternary Operator Work

How does the ternary operator work?

Boolean isValueBig = ( value > 100  ) ? true : false;

Boolean isValueBig;

if( value > 100 ) {
isValueBig = true;
} else {
isValueBig = false;
}

How does the ternary operator work

The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. Consider the statement below:

int min = (a < b) ? a : b;

What this means is: Evaluate the value of (a < b), if it's true, the value of min is a, otherwise, the value of min is b. It can be related to the if-else statement this way: If (a < b) is true: min = a; else: min is b.

Back to your question now....

em.remove(em.contains(student) ? student : em.merge(student));

This means if em.contains(student) is true, then perform em.remove(student), however if it's false, then perform em.remove(em.merge(student)).

PS:

Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. There is great argument about the "more efficient" method as seen in this post but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.

I hope this helps.. Merry coding!

Benefits of using the conditional ?: (ternary) operator

I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

Good example:

int result = Check() ? 1 : 0;

Bad example:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;

How does the ternary operator work exactly works in with multiple coupled ternary operators?

Your confusion is common and is exactly why I avoid chaining ternary operators, even when I find them readable myself.

condition1 ? yes : condition2 ? yes : condition3 ? yes : no

If it helps, think of it as having parentheses:

condition1 ? yes : (condition2 ? yes : (condition3 ? yes : no))

The second expression is the "false" action for the first expression, and the third is the "false" action for the second. It would get even harder to follow if one ternary expression were the "true" action for another.

How do you use the ? : (conditional) operator in JavaScript?

This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

Here is an example of code that could be shortened with the conditional operator:

var userType;
if (userIsYoungerThan18) {
userType = "Minor";
} else {
userType = "Adult";
}

if (userIsYoungerThan21) {
serveDrink("Grape Juice");
} else {
serveDrink("Wine");
}

This can be shortened with the ?: like so:

var userType = userIsYoungerThan18 ? "Minor" : "Adult";

serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");

Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

userIsYoungerThan21 ? serveGrapeJuice() : serveWine();

They can even be chained:

serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');

Be careful, though, or you will end up with convoluted code like this:

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;

1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

Does Python have a ternary conditional operator?

Yes, it was added in version 2.5. The expression syntax is:

a if condition else b

First condition is evaluated, then exactly one of either a or b is evaluated and returned based on the Boolean value of condition. If condition evaluates to True, then a is evaluated and returned but b is ignored, or else when b is evaluated and returned but a is ignored.

This allows short-circuiting because when condition is true only a is evaluated and b is not evaluated at all, but when condition is false only b is evaluated and a is not evaluated at all.

For example:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

Note that conditionals are an expression, not a statement. This means you can't use statements such as pass, or assignments with = (or "augmented" assignments like +=), within a conditional expression:

>>> pass if False else pass
File "<stdin>", line 1
pass if False else pass
^
SyntaxError: invalid syntax

>>> # Python parses this as `x = (1 if False else y) = 2`
>>> # The `(1 if False else x)` part is actually valid, but
>>> # it can't be on the left-hand side of `=`.
>>> x = 1 if False else y = 2
File "<stdin>", line 1
SyntaxError: cannot assign to conditional expression

>>> # If we parenthesize it instead...
>>> (x = 1) if False else (y = 2)
File "<stdin>", line 1
(x = 1) if False else (y = 2)
^
SyntaxError: invalid syntax

(In 3.8 and above, the := "walrus" operator allows simple assignment of values as an expression, which is then compatible with this syntax. But please don't write code like that; it will quickly become very difficult to understand.)

Similarly, because it is an expression, the else part is mandatory:

# Invalid syntax: we didn't specify what the value should be if the 
# condition isn't met. It doesn't matter if we can verify that
# ahead of time.
a if True

You can, however, use conditional expressions to assign a variable like so:

x = a if True else b

Or for example to return a value:

# Of course we should just use the standard library `max`;
# this is just for demonstration purposes.
def my_max(a, b):
return a if a > b else b

Think of the conditional expression as switching between two values. We can use it when we are in a 'one value or another' situation, where we will do the same thing with the result, regardless of whether the condition is met. We use the expression to compute the value, and then do something with it. If you need to do something different depending on the condition, then use a normal if statement instead.


Keep in mind that it's frowned upon by some Pythonistas for several reasons:

  • The order of the arguments is different from those of the classic condition ? a : b ternary operator from many other languages (such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the argument order).
  • Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
  • Stylistic reasons. (Although the 'inline if' can be really useful, and make your script more concise, it really does complicate your code)

If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.

Official documentation:

  • Conditional expressions
  • Is there an equivalent of C’s ”?:” ternary operator?

how this Ternary Operator work with this statemnt?

The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:

int i, k;
i = (k = 5);
System.out.println(i);
System.out.println(k);

Ideone demo

The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.

Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.


I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.

Use of ternary operator instead of if-else in C++

No. In general the conditional operator is not a replacement for an if-else.

The most striking difference is that the last two operands of the conditional operator need to have a common type. Your code does not work eg with:

std::string do_this() {return {};}
void do_that() {}

There would be an error because there is no common type for void and std::string:

<source>: In function 'int main()':
<source>:15:22: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void'
15 | my_flag ? do_this() : do_that();
| ~~~~~~~^~

Moreover, the conditional operator is often less readable.

The conditional operator can be used for complicated in-line initialization. For example you cannot write:

 int x = 0;
int y = 0;
bool condition = true;
int& ref; // error: must initialize reference
if (condition) ref = x; else ref = y; // and even then, this wouldn't to the right thing

but you can write

 int& ref = condition ? x : y;

My advice is to not use the conditional operator to save some key-strokes compared to an if-else. It is not always equivalent.

PS: The operator is called "conditional operator". The term "ternary operator" is more general, like unary or binary operator. C++ just happens to have only a single ternary operator (which is the conditional operator).

How does this nested ternary operator work using javascript?

but when does allColumns is assigned to columns?

In the remaining case, i.e. where both isUser1Readable and isUser2Readable are true.

The chained ternary expression can be interpreted as an if ... else if ... else sequence:

let columns;
if (!isUser1Readable) {
columns = allColumns.filter(column => !columnIdsUser1.includes(column.id));
} else if (!isUser2Readable) {
columns = allColumns.filter(column => !columnIdsUser2.includes(column.id));
} else {
columns = allColumns;
}


Related Topics



Leave a reply



Submit