Search code examples
javascriptif-statementoperatorsor-operator

Multiple conditions with OR || in 'if' statement JS


I am trying to write multiple conditions in the one 'if' statement with OR.

sudo code I am trying to write:

if the status is empty navigate, if the status is 'completed' navigate, if the status is 'failed' navigate.

This is my code so far:

   if ((_.isEmpty($scope.status)) || ($scope.status != ('completed' || 'failed'))) {
        return frameworkService.navigateTo('giftcardWelcome');
    }

The _.isEmpty check works, the checking if status is 'completed' works, but when checking the || for 'failed' it is not executing this.

Can someone explain to me why and how to write it correctly please? I know I could write a widened out if statement but wanted a clean refactored way.


Solution

  • The expression $scope.status != ('completed' || 'failed') really works as it looks, it does a logical OR between 'completed' and 'failed', and then compares the result of that expression against $scope.status.

    The result of 'completed' || 'failed' will be 'completed', so that means your condition is really equivalent to $scope.status != 'completed'.

    If you want to make sure that $scope.status is not equal to either string, you need to compare against each string explicitly: ($scope.status != 'completed' && $scope.status != 'failed').