Translating Confusing Conditional Shorthand


Here's the statement:

var H = dr ? ((C < 0 ? 0 : 1) - C) / dr : 0

dr and C are floats.

I don't know what "dr ?" means because it's just a float and not a true/false value.

I was wondering if someone could translate this to a traditional if-else statement thing. The "/ dr : 0" thing is confusing me too.

Leo Li's answer provides a translation, but your question seems more about using dr as a boolean when it's a "float":

I don't know what "dr ?" means because it's just a float and not a true/false value.

There's no need for it to be. JavaScript coerces values. If dr really is a number, dr ? x : y will evaluate to x if dr is not 0 and not NaN, y if dr is 0 or NaN.

More generally: Any time a value is used in a condition (whether it's the conditional operator as in your question, or if (value), or while (value), etc.), any falsy value coerces to false and any truthy value coerces to true. The falsy values are 0, NaN, "", null, undefined, and of course, false; all other values are truthy.


Here is an equivalent form:

var H;

if (dr) {
  if (C < 0) {
    H = (0 - C) / dr
  } else {
    H = (1 - C) / dr
  }
} else {
  H = 0
}

Some explanations:

  1. A conditional statement only look at if the statement (i.e. (dr) in this case) is a truthy value. Every object in JavaScript can be evaluated as true or false. It is not necessary to be a boolean type.

  2. null (Object), undefined (Undefined), NaN (Number), false (Boolean), '' (String), and +0/-0 (Number) are evaluated as false in JavaScript.

  3. Since dr is a float (i.e. a Number, there is no float primitive types), it is truthy unless it is 0 or NaN.

  4. As the question upon the ternary expression. People may consider a pseudo code:

(conditional_statement) ? (truthy_condiction) : (falsey_condiction);

By wrapped it with (), i.e. var H = dr ? (((C < 0 ? 0 : 1) - C) / dr) : 0, or just separate it by lines, as I did in the above, would make it easier to be understood.


There are many falsy values in Javascript which are equivalent to false when evaluated in a conditional expression: Falsy values

If dr is 0, or any other falsy value, H will be 0, otherwise, it will evaluate to the value of the expression ((C < 0 ? 0 : 1) - C) / dr which contains another ternary condition, which will be evaluated again in the same way