Search code examples
javascriptjscriptconditional-operatorternary

Clarify this Javascript ternary


Can someone split this nested ternary into multiple ternaries or other code or explain it in English? I've never come across a nested ternary like this so I'm not sure the order of operations:

var EqualizeCheck = (IIO.ReadDigitalInput(IO_GROUP_CHARGERS, subGroupName, IO_ITEM_ENABLEEQUALIZE) == IO_INPUT_ON) ? (EqualizeCompleteTime != "") ? (EqualizeCompleteTime <= CurrentDateTime) ? true : false : false : true;

Solution

  • To work through it step by step, first separate the most nested condition (Look for a complete condition ? value : value statement) In this case that's this bit:

    var EqualizeCheck = (IIO.ReadDigitalInput(IO_GROUP_CHARGERS, subGroupName, IO_ITEM_ENABLEEQUALIZE) == IO_INPUT_ON) ? (EqualizeCompleteTime != "") ? (EqualizeCompleteTime <= CurrentDateTime) ? true : false : false : true;

    Separate that out and repeat for each ternary condition, until you have something like this:

    // Condition 1:
    (IIO.ReadDigitalInput(IO_GROUP_CHARGERS, subGroupName, IO_ITEM_ENABLEEQUALIZE) == IO_INPUT_ON) ? 
        // Condition 1 == true, check the next condition
        // Condition 2: 
        (EqualizeCompleteTime != "") ? 
            // Condition 2 == true, check the next condition
            // Condition 3:
            (EqualizeCompleteTime <= CurrentDateTime) ? 
                // Condition 3 == true, return true
                true :
                // Condition 3 == false, return false
                false :
            // Condition 2 == false, return false
            false :
        // Condition 1 == false, return true
        true;
    

    Since this essentially boils down to two success conditions (Either where condition 1 is false, or where condition 2 and 3 are both true), you can vastly simplify it to this:

    var EqualizeCheck = 
      !IIO.ReadDigitalInput(IO_GROUP_CHARGERS, subGroupName, IO_ITEM_ENABLEEQUALIZE) == IO_INPUT_ON) ||
      ( 
        EqualizeCompleteTime != "" &&
        EqualizeCompleteTime <= CurrentDateTime
      )