Javascript has a xor operator?

4

There is an xor operator in javascript and what would be the 'symbolic' form of it (eg or has || and and tem & &)?

    
asked by anonymous 23.07.2017 / 18:02

2 answers

3

JavaScript does not have a logical XOR operator.

It has a bitwise XOR operator ^ that can perform a bitwise comparison of two numbers, but this does not help when you want to get the result of an XOR of two expressions, which do not return a number.

What you can do is create a function to do this type of logical operation:

function myXOR(x, y) {
  return (x || y) && !(x && y);
}


if (myXOR(hasValue(value1), hasValue(value2))) {
  //FAZ ALGUMA COISA
}

Here are some references for you to better understand how logical operations in JS work.

link

link

link

    
23.07.2017 / 18:14
1

You can use the ^ operator as described in this response

Eg:

var nb = 5^9 // = 12

For Boolean values you can convert with !! , which will invert the result by turning it into boolean , then flipping it back

Ex:

!!(false ^ true)
    
23.07.2017 / 18:17