Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: ternary operator inside "if" condition [duplicate]

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?

like image 552
pinker Avatar asked Apr 14 '26 11:04

pinker


1 Answers

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).

like image 66
raina77ow Avatar answered Apr 16 '26 01:04

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!