Nick
Nick

Reputation: 14293

How to determine which expression is true when multiple expressions are checked in an if statement

I was wondering (pretty much just out of curiosity) if there's a way in jquery to determine, in an if statement with multiple checks like this one

if (expression1 || expresison2 || expression3){
   ...
}

which one (or ones) are the truthy and if there's a param or something to get it inside the if statement.

for instance:

if(expression1 || expression2 || expression3){
   console.log( { the truthy expression } ) // Log in console: expression1
}

This, again, is just for my curiosity as i couldn't find anything online. I know i can split the statements or have this checked differently

Upvotes: 0

Views: 102

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

There is no jQuery here, only Javascript. One option, though an ugly one, would be to assign to a variable inside the if condition, and then print out that variable:

const a = '';
const b = 'foo';
const c = false;
let result;
if(result = (a || b || c)){
  console.log(result);
}

If at all possible, though, assign to result outside if the if statement, many linters will complain about assignment inside an if:

const a = '';
const b = 'foo';
const c = false;
const result = a || b || c;
if(result){
  console.log(result);
}

Upvotes: 2

Related Questions