I have some problems to read and understand the order of the ternary operators:
Although parentheses are not required this example increase code readability:
But for me the readability is not better! For me it is more logical to apply ((x<4) ? 10 : 8) first and then (x>2). But in this example, when I do so, I receive the same result: "8". Would it be always the same result if I begin with the inner ternary and after the with the outer. I tested with x=3 and both ways give me the same result!
Do we always apply the outside ternary operator? Or does it not matter?
(x>2) is true and now between which two numbers I have to select: 8 and 7? If this is right, I get "8". Then the second (x<4) is false and I now have only 10 and 8. Since (x<4) is false, I get "8" and "8" is the right answer.
But when I change the value of x to 1:
(x>2) is false also I get "7". (x<4) is true, then between 10 and 7 I get "10"?! But the right answer is "7". Why?
IS THIS THE ANSWER: When the first (x>2) is false the second (x<4) may never be evaluated?!
Now we have two ternary operators chained, is it also possible to chain more? But the more they are the more difficult is is it to read und understand.
you can always arrange the ternaries so that it becomes much more readable. For instance: in your example, and to answer your question, you could transform it to:
I always write my ternaries like this:
where a, b anc c are boolean expressions. As if it were a switch statement!
I hate signatures!
There's a hole in the bucket, dear Liza, dear Liza, a hole in the bucket, dear liza, a tiny ad:
Devious Experiments for a Truly Passive Greenhouse!