Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between (|) Bitwise OR vs (^) Bitwise XOR in JavaScript

I'm really getting confused on the use of the | OR vs ^ XOR in JavaScript, illustrated in the simple example below;

(function sayHi(n){
if(n < 1)   //base case
    return;
console.log("Hi!!" | "Hello!!") ;
sayHi(n - 1);   //recurse
})(5);


(function sayHi(n){
if(n < 1)   //base case
    return;
console.log("Hi!!" ^ "Hello!!") ;
sayHi(n - 1);   //recurse
})(5);

(function sayHi(n){
if(n < 1)   //base case
    return;
console.log(2 | 6) ;
sayHi(n - 1);   //recurse
})(5);


(function sayHi(n){
if(n < 1)   //base case
    return;
console.log(2 ^ 6) ;
sayHi(n - 1);   //recurse
})(5);

I'm confused about when, how, why, where I should appropriate use | vs ^.

Can someone please help me make sense the major difference between OR and XOR operations?

I was reading the documentation for JavaScript from MDN web Docs to better understand the concept of bitwise operations, but I am struggling to understand their significant difference.

I just want to make sure I continue to use these operations correctly henceforth.

Thanks a lot for the anticipated help!

like image 412
antzshrek Avatar asked Dec 05 '25 09:12

antzshrek


1 Answers

OR and XOR are different operators:

  • OR:

    0 | 0 = 0
    0 | 1 = 1
    1 | 0 = 1
    1 | 1 = 1
    
  • XOR

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

If you have two bits and combine these with OR, the result will be 1, if one of these bits or both are 1. If you combine them with XOR (Exclusive OR) then it will be 1 if only one of these bits are 1 (not if both).

like image 55
Joshua K Avatar answered Dec 07 '25 22:12

Joshua K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!