I was just wondering if this was possible because i started using ternary operators to reduce lines of code and i am loving it.
if (x==y)
{
z += x;
} else if (x==z)
{
z += y;
} else {
z += 1;
}
i can do this now if there is only one if statement like this:
z = x == y ? z += x : z += 1;
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.
Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.
Yes you can. A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion). Save this answer.
It would be like this:
z =
x == y ? z + x :
x == z ? z + y :
z + 1;
If you use z += x
as an operand it will end up doing z = (z += x)
. While it works in this special case, as the result of the expression z += x
is the final value of z
, it may not work in other cases.
Howver, as all operations have the z +=
in common, you can do like this:
z +=
x == y ? x :
x == z ? y :
1;
Use with care, though. The code is often more readable and maintainable the simpler it is, and nested conditional operations are not very readable. Also, use this only when you have an expression as the result of the conditional operation, it's not a drop-in replacement for the if
statement.
You can use
z += x == y ? x : x == z ? y : 1;
But honestly, that's not really more readable than what you had before. You can make it slightly clearer by adding parentheses:
z += x == y ? x : (x == z ? y : 1);
But generally I'd stay away from nested conditional operators unless when golfing.
Four lines of code, and the most readable, IMO. No need for a ternary operator here:
if (x == y || x == z)
z += y;
else
z++;
If I had to write it using ternary, I would do:
z += (x == y || x == z) ? y : 1;
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