Whats a Double arrow in javascript

What do the operators “>>” (double arrow) and “|” (single pipe) mean in JavaScript?

If that’s the question that runs through your mind, then you are at the right place to discover Bitwise operators.

1. The Right Shift Operator >>(double arrow)

Shifts x in binary representation y (< 32) bits to the right, discarding bits shifted off.
Or more simply x >> y means to shift the bits of x by y places to the right

For example, 35 >> 2
Here, 35 = 100011. 
Shifting the bits to the right by 2 places gives us -> 001000 
Note that we discarded the last 2 bits .i.e. 11.
And 001000 = 8.
Hence, 35 >> 2 = 8!

2. The Left Shift Operator <<

Shifts x in binary representation y (< 32) bits to the left, shifting in zeroes from the right.

For example, 9 << 2
Here, 9 = 1001. Shifting the bits to the left by 2 places gives us, 100100 
Note that we added zeros for the last 2 bits
And 100100 = 36.
Hence, 9 << 2 = 36!

3. Bitwise OR Operator |

Returns 1 in each bit position for which the corresponding bits of either or both operands are 1. (OR’s truth table)

For example, 9 | 14
Here,   9 = 1001
       14 = 1110
Result:     1111
And 1111 = 15.
Hence, 9 | 14 = 15!

4. Bitwise And Operator &

Returns 1 in each bit position for which the corresponding bits of both operands are 1, else returns 0. (AND’s truth Table)

For example, 9 & 14
Here,   9 = 1001
       14 = 1110
Result:     1000
And 1000 = 8.
Hence, 9 & 14 = 8!

5. Bitwise XOR Operator ^

Returns 1 in each bit position for which the corresponding bits of either but not both operands are 1. (XOR truth Table)

For example, 9 ^ 14
Here,   9 = 1001
       14 = 1110
Result:     0111
And 0111 = 7.
Hence, 9 ^ 14 = 7!

6. Bitwise NOT Operator ~

Inverts the bits of its operand. i.e. 0 becomes 1 and 1 becomes 0.

For example, ~5
Here,   5 = 0101
Result:     1010 (after inverting bits)
And 1010 = -6 
Hence, ~5 = -6!

1010 = -6 (This may confuse some of you, but this is how Negative numbers are represented in Two’s complement )

Bitwise Operators are well known for their speed of execution. They are considerably fast compared to their Math equivalents.
Well supported by all Desktop and Mobile Browsers. And they totally help you in writing shorter code!

Follow the link to check out some real use cases of Bitwise Operators. Another interesting post for the keen!

Reference

Leave a Reply