3

So, as far as I checked, there is no XOR operator for javascript.

There is tho the following -

if( ( foo && !bar ) || ( !foo && bar ) ) { ... }

This is clear if foo and bar are boolean values. But can XOR be used to check against a different type of expression? For example if I would like to check a value against another value, that is -

if (type === 'configuration' XOR type2 === 'setup') { ... }

Would it transform to something like -

if ( (type === 'configuration' && type2 !== 'setup') || (type !== 'configuration' && type2 === 'setup' ) ) { ... } Or would it look different?

This gives the following result -

type = 'configuration' && type2 = 'setup': false type = 'configurations' && type2 = 'setup': true type = 'configuration' && type2 = 'setups': true type = 'configurations' && type2 = 'setups': false

Which matches the

0 XOR 0 = 0 0 XOR 1 = 1 1 XOR 0 = 1 1 XOR 1 = 0

but I'm not sure if this will match for all cases.

Patiss
  • 187
  • 3
  • 13
  • Read here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators – Asons Jul 04 '18 at 08:16
  • You could define `const xor = (a, b) => a && !b || !a && b` and then just use it `xor(type === 'configuration', type2 === 'setup')`. This is simple, reusable, maintainable and easy to read. Unlike bitwise operators and long logical expressions. – Yury Tarabanko Jul 04 '18 at 08:29

1 Answers1

5

The easiest logical xor is:

a !== b

Or in your case:

if((type === 'configuration') !== (type2 === 'setup'))

There is also a bitwise xor (^) in javascript that works here too, as booleans are typecasted to 0 / 1 and vice versa:

if((type === "configuration") ^ (type2 === "setup"))
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Hmm, so that's the same what I wrote, I guess? The ^ looks a great solution, since it's shorter and more clearer. Was it introduced in a specific ECMAscript version? – Patiss Jul 04 '18 at 08:20
  • 4
    @Jogn It might be shorter, but I don't think it's clearer, unless you're in a team that you're sure already understands bitwise operators at a glance. Write code for *clear readability*, not for golfing. – CertainPerformance Jul 04 '18 at 08:22
  • @jogn I learned JS ~5/6 Years ago, and exists since then – Jonas Wilms Jul 04 '18 at 08:25
  • 1
    For a great article on xor in Javascript see: http://www.howtocreate.co.uk/xor.html – nevf Apr 10 '19 at 00:23