0

>>>= is the unsigned right shift operator in Javascript: Reference

In this code I see that the author is using this code:

if (typeof offset !== 'number' || offset % 1 !== 0)
  throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
  throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);

I wonder what's the point of the use of the >>>=, and whether I could skip it entirely. The code seems to have effect only in case the offset is negative, and it's not very clear to me the purpose of that operation.

GNi33
  • 4,459
  • 2
  • 31
  • 44
saste
  • 710
  • 2
  • 11
  • 19
  • Maybe not a duplicate, but it contains a part of the answer :">>> 0 is unique in that it is the only operator that will convert any type to a positive integer:" - but why convert it and then check if it is negative? I would remove that line like you said. – pdem Apr 20 '15 at 11:39

1 Answers1

2

The only purpose for shifting a value zero steps would be to force the conversion to a 32-bit integer and back.

As the statement before that checks that it's a number and that the number has no fractional part, it serves no purpose in that code.

For a negative value it would convert it to the unsigned two's complement of the value, e.g. from -1 to 4294967295. As that is outside the size of the buffer anyway, it would be caught by the check in the next statement.

If you keep the shift, then you don't need the check offset < 0 in the next statement, as that can never happen.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005