I have a program flow as follows:
if(a)
{
if((a > b) || (a > c))
{
doSomething();
}
statementX;
statementY;
}
I need to translate this into a conditional expression, and this is what I have done:
(a) ? (((a > b) || (a > c)) ? doSomething() : something_else) : something_else;
Where do I insert statements statementX, statementY? As it is required to execute in both the possible cases, I cannot really find out a way.
Yes, we can, but with one proviso… There is no block demarcation so that action should be simple, else it would be better to abstract it away in a function and call the function from the ternary. Something we commonly see is console.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
A Ternary Operator in Javascript is a special operator which accepts three operands. It is also known as the "conditional" or "inline-if" operator. Ternary Operator in Javascript makes our code clean and simpler. It can be chained like an if-else if....else if-else block.
The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.
You can use comma ,
operator like this:
a ? (
(a > b || a > c ? do_something : do_something_else),
statementX,
statementY
)
: something_else;
The following program:
#include <stdio.h>
int main ()
{
int a, b, c;
a = 1, b = 0, c = 0;
a ? (
(a > b || a > c ? printf ("foo\n") : printf ("bar\n")),
printf ("x\n"),
printf ("y\n")
)
: printf ("foobar\n");
}
print for me:
foo
x
y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With