This sample code from Mozilla's JS reference uses the >> and >>> operators with a RHS argument of 0. I guess this is an alternative to Math.floor() that has a performance advantage because it uses a built-in operator instead of having to look up a function. But what difference does >> vs >>> make with a zero shift?
-
2They are great for code-golf :) – Jonathan.Brink Jan 14 '16 at 18:30
-
1The difference is in how they treat negative numbers. In the polyfill, the arrays length can never be less than `0` (empty array), so using `>>>` is fine, but someone could pass in a negative number for `target`, so preserving the sign is crucial, hence the use of `>>`. As an example, `-3 >> 0` is still `-3`, but `-3 >>> 0` returns `4294967293` because of the way zeroes are shifted in on the left, so that could potentially create an unexpected result for the `target` variable. – adeneo Jan 14 '16 at 19:16
2 Answers
From the MDN Article:
>>
is a Sign-propagating right shift:
Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
>>>
is a Zero-fill right shift:
Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeroes from the left.
So the difference is that one will shift in zeroes from the left.
From this stackoverflow answer talking about a zero-shift:
So doing a bitwise operation with no actual effect, like a rightward-shift of 0 bits >>0, is a quick way to round a number and ensure it is in the 32-bit int range. Additionally, the triple >>> operator, after doing its unsigned operation, converts the results of its calculation to Number as an unsigned integer rather than the signed integer the others do, so it can be used to convert negatives to the 32-bit-two's-complement version as a large Number. Using >>>0 ensures you've got an integer between 0 and 0xFFFFFFFF.
-
The other one will also shift in zeroes from the left for half its inputs – Paul Jan 14 '16 at 18:30
-
1This doesn't answer the question: what difference does it make with a zero shift? – Brent Washburne Jan 14 '16 at 18:33
It converts them to numbers that can be expressed as 32-bit unsigned ints. So yes it will make it a (typeof number) as a floored int, it will also make it a 32-bit unsigned, which JS programming loves :)
The main difference is the signed vs unsigned.

- 412
- 2
- 9