Kalle Kalle - 1 month ago 13
Javascript Question

boolean logic, true if 1 out of 4 are true

I have 4 variables, any of them can be true or false

var a
var b
var c
var d


I would like to test 3 conditions:


  1. true if 1 out of 4 is true

  2. true if 2 out of 4 is true

  3. true if 3 out of 4 is true



I know that 0 out of 4 is true when:

a!=true && b!=true && c!=true && d!=true


and
4 out of 4 are true when:

a==true && b==true && c==true && d==true


but i cant think further.

Answer

You could just add the variables with boolean values. The result is a number.

value = a + b + c + d;

Then you could make a check agains the number, you want to test.

var a = false, b = true, c = true, d = true,
    value = a + b + c + d;

console.log(value);