I found this Javacript code and I am unable to understand what it means to have a ternary operator inside an if condition.
var s = 10, r = 0, c = 1, h = 1, o = 1;
if (s > r ? (c = 5, h = 2) : h = 1, o >= h)
{
alert(1);
}
Is the o >= h the result being returned to evaluate in the "if" condition?
And what about the use of comma in "if" condition?
It's really just a syntaxic short-cut. One can expand this into two if statements:
var condition;
if (s > r) {
c = 5;
condition = (h = 2); // another short-cut; it's essentially (h = 2, condition = true)
}
else {
h = 1;
condition = (o >= h);
}
if (condition) {
alert(1);
}
Using comma allows to turn two statements into a single one (as a, b always evaluates to b, though both a and b sub-expressions are evaluated in process).
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