Why is there no logical xor in JavaScript?

前端 未结 19 2130
忘了有多久
忘了有多久 2020-11-29 17:17

Why is there no logical xor in JavaScript?

19条回答
  •  臣服心动
    2020-11-29 17:27

    Yes, Just do the following. Assuming that you are dealing with booleans A and B, then A XOR B value can be calculated in JavaScript using the following

    var xor1 = !(a === b);
    

    The previous line is also equivalent to the following

    var xor2 = (!a !== !b);
    

    Personally, I prefer xor1 since I have to type less characters. I believe that xor1 is also faster too. It's just performing two calculations. xor2 is performing three calculations.

    Visual Explanation ... Read the table bellow (where 0 stands for false and 1 stands for true) and compare the 3rd and 5th columns.

    !(A === B):

    | A | B | A XOR B | A === B | !(A === B) |
    ------------------------------------------
    | 0 | 0 |    0    |    1    |      0     |
    | 0 | 1 |    1    |    0    |      1     |
    | 1 | 0 |    1    |    0    |      1     |
    | 1 | 1 |    0    |    1    |      0     |
    ------------------------------------------
    

    Enjoy.

提交回复
热议问题