Michał B
Michał B

Reputation: 473

Check which condition in IF statement is true

Is there any method in JavaScript to define which condition inside IF statement is fulfilled?

For example:

if(a === 1 || b === 2) {
  // do something apart of fulfilled condition
  if(a === 1) {
    // do something
  } else if(b === 2) {
    // do something else
  }
} 

Code above working as expected but I'm wondering if there is a clever way to do this easier, especially when there will be more conditions.

Thanks for answers.

Upvotes: 0

Views: 453

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22265

you can use Boolean algebra:

let a = 1 , b=24;

let binTests = 0;
binTests |= (a===1)?1:0;
binTests |= (b===2)?2:0;

console.log ( (binTests & 1) ? '(a===1) is true ' : '(a===1) is false '  ) 
console.log ( (binTests & 2) ? '(b===2) is true ' : '(b===2) is false '  ) 

Upvotes: 0

Pointy
Pointy

Reputation: 413682

No, there is no provided way to do what you ask other than making explicit tests. In this specific case, the following is equivalent:

if (a === 1) {
  // do something
}
else if (b === 2) {
  // do something else
}

Upvotes: 2

Related Questions