JavaScript Tutorial JavaScript References

JavaScript - Bitwise AND assignment operator



The Bitwise AND assignment operator (&=) assigns the first operand a value equal to the result of Bitwise AND operation of two operands.

(x &= y) is equivalent to (x = x & y)

The Bitwise AND operator (&) is a binary operator which takes two bit patterns of equal length and performs the logical AND operation on each pair of corresponding bits. It returns 1 if both bits at the same position are 1, else returns 0.

Bit_1Bit_2Bit_1 & Bit_2
000
100
010
111

The example below describes how bitwise AND operator works:

50 & 25 returns 16

     50    ->    110010  (In Binary)
   & 25    ->  & 011001  (In Binary)
    ----        --------
     16    <-    010000  (In Binary)  

The code of using Bitwise AND assignment operator (&=) is given below:

var x = 50;
var y = 25;
var txt;

//Bitwise AND assignment operation
x &= y;
txt = "x = " + x;

The output (value of txt) after running above script will be:

x = 16

Example: Check if a number is even or odd

The last bit of an even number is always 0, whereas for an odd number the last bit is always 1. Therefore, for a given number n, (n & 1) returns 0 if the n is even, else returns 1.

Even Number: 

     50   ->    110010  (In Binary)
    & 1   ->  & 000001  (In Binary)
    ----       --------
      0   <-    000000

Odd Number: 

     99   ->    1100011  (In Binary)
    & 1   ->  & 0000001  (In Binary)
    ----       ---------
      1   <-    0000001

The below code checks whether a given number is even or odd:

function CheckEven(MyNum) {
  var x = MyNum;
  x &= 1;
  if (x == 1) 
    return MyNum + " is an odd number.<br>";
  else 
    return MyNum + " is an even number.<br>";
}

var txt;
txt = CheckEven(50);
txt = txt + CheckEven(99);

The output (value of txt) after running above script will be:

50 is an even number.
99 is an odd number.

❮ JavaScript - Operators