3

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?

dhilt
  • 18,707
  • 8
  • 70
  • 85
pinker
  • 1,283
  • 2
  • 15
  • 32
  • 1
    1) yes; 2) assignment of 1 to `h`. – raina77ow Dec 23 '15 at 17:00
  • Please read about ternary operators in JS before posting. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – SoluableNonagon Dec 23 '15 at 17:01
  • 2
    See [How to use the ?: (ternary) operator in JavaScript](http://stackoverflow.com/q/6259982/1529630) and [What does a comma do in JavaScript expressions?](http://stackoverflow.com/q/3561043/1529630) – Oriol Dec 23 '15 at 17:02
  • 1
    Sorry, but I voted to close it as a duplicate (because it is explained really well in the two linked answers). If you have any specific question not covered by those ones, please explain it and we'll reopen it. – raina77ow Dec 23 '15 at 17:05
  • Why do people go out of their way to make code that's hard to understand? `h=2` doesn't make any sense in terms of an `if` statement. – Andy Dec 23 '15 at 17:08
  • @Andy All `s>r ? (c=5,h=2) : h=1` should be moved before the `if`. – Oriol Dec 23 '15 at 17:09

2 Answers2

4

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

raina77ow
  • 103,633
  • 15
  • 192
  • 229
-1

This code will not give error when u run ... basically ... what is does is run the ternary operation where it finds (c=5,h=2) which is not a condition to write in if statement ..
hence the condition wont satisfy and it wont alert(1);

Satyam S
  • 267
  • 3
  • 18