Search code examples
javascriptoperatorscalculator

Why is 0:0 ignored as an operator?


I'm using this Drupal module that's called Webform Calculator, and it makes us of so-called operators.

There's one formula based on operators that almost does the job:

({total_weight}==0? 0:0) || ({total_weight}<=2? 5:0) || ({total_weight}<=10? 6:0) || ({total_weight}<=30? 10.5:0) 

This is what it's doing right:

  • If the total weight equals or is less than 2, use 5
  • If the total weight equals or is less than 10, use 6
  • If the total weight equals or is less than 30, use 5
  • If the total weight is more than 30, use 0

The only that it doesn't work out (which is actually the first part of the formula):

  • If the total weight equals 0, use 0

It keeps throwing 5 at me. Anyone has an idea what I'm getting wrong, and what this is called in the first place (having a hard time finding references on Google)?


Solution

  • ({total_weight}==0? 0:0) || ({total_weight}<=2? 5:0) || ({total_weight}<=10? 6:0) || ({total_weight}<=30? 10.5:0)
    

    If total_weight is 0 then it can be interpreted as:

    (0 || ({total_weight}<=2? 5:0) || ({total_weight}<=10? 6:0) || ({total_weight}<=30? 10.5:0)
    

    or

      (false || ({total_weight}<=2? 5:0) || ({total_weight}<=10? 6:0) || ({total_weight}<=30? 10.5:0)
    

    Which causes the 2nd condition to execute. 0<=2 so the ternary "returns" 5