3

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.

5
  • Isn't 1+1 supposed to be 1 in boolean addition? Commented Jan 15, 2014 at 12:25
  • 1
    @basilikum No. 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1 and 1 + 1 = 0 (with a carry over of 1). Hence boolean addition is the xor operator and the carry can be found using boolean multiplication (i.e. the and operator). Commented Jan 15, 2014 at 12:28
  • @AaditMShah Hmm...ok, but then why does every source I find say that boolean addition is equivalent to OR and that 1+1 equals 1. Commented Jan 15, 2014 at 12:29
  • @basilikum Because boolean multiplication is and and boolean addition is in fact or. However I believe that the OP is looking to create a half adder. This requires the xor operation. Commented Jan 15, 2014 at 12:31
  • OR is obviously OR whilst + is something else. (The carry part mentioned above etc. Yes half-adder) Commented Jan 16, 2014 at 14:31

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is not the same as boolean addition. Boolean addition is the xor operator.
@AaditMShah I think the equivalent to a boolean addition really is the OR operator. Look at this for example: allaboutcircuits.com/vol_4/chpt_7/2.html
@basilikum I understand what you're trying to say but I believe that the OP is looking to create an adder in JavaScript. Hence the sum is found using xor and the carry is found using and. See: en.wikipedia.org/wiki/Adder_(electronics)
@VisioN yes that's right. But OR still seems to be equivalent to a boolean addition. Just google "boolean addition". However, if OP really wants 1+1 to be equal to 0, than he probably doesn't really look for a boolean addition, since this would give 1 as a result.
I actually ended up doing just (bool1+bool2+bool3)%2
2

What you're looking for is the xor operator:

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

Comments

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

for boolean this can be achieved by using Short-circuit AND and OR operators.

function myXOR(a,b) {   
       return ( a || b ) && !( a && b );    
}
myXOR(true,true) == false

Comments

0

you can code yor for bool like this:

function xor(a,b) {
  if (a === true && b === true) {
     return false;
   }
 return a || b;   
}

OR in typescript:

   xor(a: boolean,b: boolean): boolean {
     if (a === true && b === true) {
       return false;
     }
     return a || b;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.