javascriptif-statementserena

If Statement within Case of Switch - JS


Can you use IF statements within a case of a Switch.

Both of the first statements of each case work fine, but the else IF statements do not :s

Any help would be greatly appreciated!

switch (units) {
    case "Days" :
            if (CarryQuantity > 5)  {MakeFieldInvalid("CARRY_OVER", "You can only carry over a maximum of 5 days"); 
                }

                else if (CarryQuantity = 0) { MakeFieldInvalid("CARRY_OVER", "The value of holiday carry-over days must be greater than zero"); 
                }

                    else  {MakeFieldValid("CARRY_OVER");
                }

        break;
    case "Hours" :
            if (RGBCarryQuantity > 40)  {MakeFieldInvalid("RGB_CARRY_QUANTITY_2", "You can only carry over a maximum of 40 hours.");
                }

                else if (RGBCarryQuantity = 0)  {MakeFieldInvalid("RGB_CARRY_QUANTITY_2", "The value of holiday carry-over hours must be greater than zero");
                }

                    else {MakeFieldValid("RGB_CARRY_QUANTITY_2");
                }

        break;
    default :
        MakeFieldValid("CARRY_OVER");
        MakeFieldValid("RGB_CARRY_QUANTITY_2");
}

}

Solution

  • Yes, you can.

    Please note that '=' is an assigment operator. For comparing values, use either equality '==' or '===' which is the identity operator.

    So you have problem in the else if statements:

    else if (CarryQuantity = 0)
    

    that should be:

    else if (CarryQuantity == 0)
    

    which handles automatic type conversion or

    else if (CarryQuantity === 0)
    

    which can be used if CarryQuantity is a number and not a string.