26

What does this: >> mean in JavaScript?

Seen in this context:

document.onkeydown = document.onkeyup = function(e,v,y,k) {
  (i=e.keyCode-37)>>2 || (keys[i] = e.type[5]&&1||(0))
}
bcm
  • 5,470
  • 10
  • 59
  • 92

4 Answers4

25

>> is the bitwise right shift operator.

For example: 4 >> 1 equals 2 because 4 is 100 in binary notation, which is shifted one bit to the right, giving us 10 = 2

Mårten Wikström
  • 11,074
  • 5
  • 47
  • 87
  • what is the significance by getting the binary notation conversion, in this context, and then using the bitwise right shift operator? – bcm Apr 03 '11 at 07:23
  • I don't see a reason for it. They could have written it as (i=e.keyCode-37)/4 instead, since right shifting two bits is essentially the same as dividing by four. – Mårten Wikström Apr 03 '11 at 07:33
23

Javascript Bitwise Operators

Left shift a << b Shifts a in binary representation b (< 32) bits to the left, shifting in zeros from the right.

Sign-propagating right shift a >> b Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.

amosrivera
  • 26,114
  • 9
  • 67
  • 76
3
(i=e.keyCode-37)>>2

This code is discarding the two least significant bits of i (similar to dividing by 4), and comparing the result to zero. This will be false when the key pressed is 37-40 (arrow keys), and true otherwise.

Phssthpok
  • 1,629
  • 1
  • 14
  • 21
0

It's the Bitwise shift operator (see here).

Now, as to exactly what it's doing here I'm not sure... I'm sure some of our larger-brained bretheren that actually finished college could help us out with that. ;^)

Jim Davis
  • 1,230
  • 6
  • 11