Mark As Completed Discussion

Bitwise shift operators

All bitwise shift operators in JavaScript move individual bits left or right by a number of bit positions that you specify.

<< (Left shift)

Left shift (<<) shifts bits of the first operand to the left. The value of the second operand determines how many positions the bits are shifted. Bits shifted off to the left are discarded. Positions that free up to the right are populated with zero bits.

Let's look at an example: what exactly does 7 << 2 do in JavaScript?

  1. The first (left) operand is converted to binary form: 7 in binary is 111. In fact, the entire binary number has 32 bits, but the remaining bits to the left are all zeros:

    SNIPPET
    10000000000000000000000000000111
  2. Because the second operand is 2, two leftmost bits are now stripped off, leaving us with 30 bits:

    SNIPPET
    1-0000000000000000000000000000111
    2+00000000000000000000000000111
  3. To fill the vacant 2 bits, zeros are inserted in the two rightmost positions:

    SNIPPET
    1-00000000000000000000000000111
    2+0000000000000000000000000011100
  4. The result, 11100, is now converted to decimal 28 and returned.

As a general rule, applying Left shift to x by y bits returns x multiplied by the yth power of 2:

x << y = x×2y

In our example above, this rule translates to:

7 << 2 = 7×22 = 7 × 4 = 28

>> (Sign-propagating right shift)

Sign-propagating right shift (>>) shifts bits of the first operand to the right by the number of positions defined by the second operand. Bits shifted off to the right are discarded. Bit positions that free up on the left are filled with copies of the bit that was previously leftmost.

Because the leftmost bit defines the sign of the number, the resulting sign never changes, which explains "sign-propagating" in the operator's name.

For example, 242 >> 3 returns 30:

SNIPPET
1-0000000000000000000000011110010
2+0000000000000000000000000011110

>>> (Zero-fill right shift)

Similar to the previous operator, Zero-fill right shift (>>>) shifts bits of the first operand to the right by the number of positions defined by the second operand. However, vacant bit positions on the left are filled with zeros. This has two implications:

  1. The result will always be positive, because a zero in the leftmost bit means a positive number.
  2. For positive numbers, both right shift operators, >> and >>>, always return the same result.

For (a somewhat wild) example, -9 >>> 2 returns... 1073741821:

SNIPPET
1-11111111111111111111111111110111
2+00111111111111111111111111111101

Enough with the theory though, let's discuss practice.