Can we implement Boolean XOR in Javascript ? Yes , we can implement ,As we know that JavaScript provides a boolean AND operator (&&), a boolean OR operator (||), and a boolean NOT operator (!). But it is missing a boolean XOR operation. (In English, XOR can be stated as "If A is true or B is true, but not if both are true.") ,Before doing this we should have a little bit knowledge of javascript prototype . The following simple code adds an XOR() method to the Boolean object .
Boolean.prototype.XOR=function(bool2){var bool1=this.valueOf();return (bool1==true && bool2==false) || (bool2==true && bool1==false);//return (bool1 && !bool2) || (bool2 && !bool1);}true.XOR(false); //returns a value of true
(The above method requires the passed value to be an actual boolean value to succeed. The second option, commented out, will attempt to cast bool2 to a boolean value for the comparison. If that line were used instead, values of 0, null, '' and undefined would be interpretted as false, and other non-empty values such as 1 or "foo" will be interpretted as a value of true.)