Search code examples
javascriptor-operator

JavaScript OR Operator correct, but if statement not behaving as expected


I am working in a JavaScript heavy application, and I have the following code:

function displayingNotes() {
    if (!($scope.overseasTravelTask.RegisteredKeeperName.toLowerCase()
           .indexOf("zenith") > -1 || 
         $scope.overseasTravelTask.RegisteredKeeperAddressLine1.toLowerCase()
           .indexOf("zenith")
       )
    ) 
    {
       $scope.calloutClass = 'callout-danger';
       $scope.calloutMessage = 'We (Zenith) cannot provide this vehicle with the necessary documents.';
       $scope.disableNextBtn = true;
    } 
    else 
    {
       $scope.calloutMessage = 'Please ask driver about this.';
    }
}

For the if statement, I am placing a break-point and checking my logic in the Chrome console, and logic looks correct, but when I click the F10 button, I expect to get inside the if statement, instead I jump over it!


Solution

  • The second operand to your || is:

    $scope.overseasTravelTask.RegisteredKeeperAddressLine1.toLowerCase().indexOf("zenith")
    

    ...which will result in a number: The index of the substring, or -1 if not found. So when coerced to a boolean, it will be true for all cases (-1, 23, 42, etc.) other than when the substring happens to be found at index 0, in which case it will be false.

    You probably wanted a !== -1 in there.