JS syntax for "if a or b or c but not all of them"

Viewed 38

So, I am super new to JS! I am trying to write a syntax to check if only one of the three variable is present.

if a and (not b or not c) or b and (not a or not c) or c and (not a or not b)
2 Answers

Try this out:

if ((a || b || c) && !(a && b && c)) {

}

Here's a test:

function specialBool(a, b, c, message){
  if ((a || b || c) && !(a && b && c)) {
    console.log(message)
  }
}

specialBool(true, false, false, 'One true');
specialBool(true, true, false, 'Two true');
specialBool(true, true, true, 'All true'); // Shouldn't log

Convert them to booleans, then add them up, and check that the result is 1. (true will be coerced to 1; false will be coerced to 0.)

if (Number(Boolean(a)) + Number(Boolean(b)) + Number(Boolean(c)) === 1) {
  // ...
}

or

const sum = [a, b, c].reduce((sum, item) => sum + Number(Boolean(item)), 0);
if (sum === 1) {
  // ...
}
Related