I know that && and || are used in comparisons as AND and OR, respectively.
But what about the & and | operators? What are they used for?
Here's the code I'm testing:
var a = 2;
var b = 3;
var c = a & b;//2
var d = a | b;//3
Difference between && , || and &, | ....
They are bitwise operators that operate on the bits of the number. You have to think the bits of the numbers in order for the result to make sense:
a = 2 //0010
b = 3 //0011
a & b; //0010 & 0011 === 0010 === 2
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
They are mainly used for reading and manipulating binary data, such as .mp3 files.
They are bitwise AND and OR respectively. The usage is mainly for low-level (now don't why you would want that here, there may be many applications) operations.
For example:
Decimal Number Binary Form
20 10100
30 11110
20 ==> 10100
& 30 ==> 11110
----- ----------
20 10100 (when both bits are 1)
20 ==> 10100
| 30 ==> 11110
----- ----------
30 11110 (when either of the bits is 1)
Similarly there are other operators too:
operator meaning example
xor (^) only one bit is 1 1101
^1001
------
0100
I could provide the whole list but that would be of no use. Already many answers contain links to excellent resources. You might want to look at those. My answer just gives some idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With