Search code examples
javascriptboolean-logic

Boolean addition in Javascript


How do i do a clean boolean add in javascript?

1+1 = 0;
1+0 = 1;
1+1+1 = 1;

etc. can one just sum booleans?

true+true = false
false+true = true;

etc.


Solution

  • Just use bitwise XOR operator:

    1 ^ 1 = 0
    1 ^ 0 = 1
    1 ^ 1 ^ 1 = 1
    

    FWIW: The same works for most high-level programming languages.