The bitwise AND operator is & and works on two values.
Bitwise AND uses the following truth table to perform an AND operation.
Bit From First Number | Bit From Second Number | Result |
---|---|---|
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
The result will be 1 only if both bits are 1. If either bit is 0, then the result is 0.
The following example uses AND on the numbers 25 and 3:
var result = 25 & 3; console.log(result); //1
Here is how it worked.
25 = 0000 0000 0000 0000 0000 0000 0001 1001 3 = 0000 0000 0000 0000 0000 0000 0000 0011 --------------------------------------------- AND = 0000 0000 0000 0000 0000 0000 0000 0001
Every other bit of the resulting number is set to 0, making the result equal to 1.