Kirsten
Kirsten

Reputation: 181

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.

Upvotes: 1

Views: 104

Answers (3)

Jaromanda X
Jaromanda X

Reputation: 1

('completed' || 'failed') === 'completed' - because that's how javascript works - you need to check equality individually ...

You'll need

|| ($scope.status != 'completed' &&  $scope.status != 'failed')

note && not || ... because $scope.status != 'completed' || $scope.status != 'failed' will ALWAYS be true - because of logic

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409136

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').

Upvotes: 1

Amadan
Amadan

Reputation: 198294

$scope.status != ('completed' || 'failed')

This does not do what you think it does. In JavaScript A || B returns A if it is truthy, otherwise B; since 'completed' is truthy, this is equivalent to

$scope.status != 'completed'

In order to check whether $scope.status is one of the two values, you need to either check both are different explicitly (note &&, not ||):

$scope.status != 'completed' && $scope.status != 'failed')

or test that it is not in a set (or another container):

let endSet = new Set(['completed', 'failed']);
// ...

endSet.has($scope.status)

Upvotes: 1

Related Questions