javascriptsahi

Compare function failing when null value passed to one of the parameters


i am using the below code for comparing two values:

function CompareValue($ValueTobePresent,$ExpectedValue)
{
    var $ValueTobePresent=$ValueTobePresent.toLocaleLowerCase();
    var $ExpectedValue = $ExpectedValue.toLocaleLowerCase();
    _assertEqual($ValueTobePresent, $ExpectedValue);

}

Now my problem is if a null value is passed the function fails with the below message: Logging exception: Cannot call method "toLocaleLowerCase" of null [81 ms] Cannot call method "toLocaleLowerCase" of null.

Is there a way i can solve it out so that i can handle the null values also? Also i have around 25 comparisons to do so i want the code not to be very time consuming.

Thanks


Solution

    1. Remove var inside the function
    2. Use ternary operator to check if arguments passed are valid
    3. Use toString() before calling toLocaleLowerCase()

    Code:

    function CompareValue($ValueTobePresent, $ExpectedValue) {
        $ValueTobePresent = $ValueTobePresent ? $ValueTobePresent.toString().toLocaleLowerCase() : '';
        $ExpectedValue = $ExpectedValue ? $ExpectedValue.toString().toLocaleLowerCase() : '';
        _assertEqual($ValueTobePresent, $ExpectedValue);
    }