5

While I was checking the lodash code, I came up with a question I was curious about.

// slice.js
function slice(array, start, end) {
  let length = array == null ? 0 : array.length
  if (!length) {
    return []
  }
  start = start == null ? 0 : start
  end = end === undefined ? length : end

  if (start < 0) {
    start = -start > length ? 0 : (length + start)
  }
  end = end > length ? length : end
  if (end < 0) {
    end += length
  }
  length = start > end ? 0 : ((end - start) >>> 0)
  start >>>= 0

  let index = -1
  const result = new Array(length)
  while (++index < length) {
    result[index] = array[index + start]
  }
  return result
}

export default slice
  1. Specifically, I am curious about why this code exists in this part.
((end - start) >>> 0)

As far as I know, the bit operator shifts the position of a binary number, but I am curious why it shifts 0 times.

  1. >>>=
  • And >>>= This operator is the first time I saw it. Does anyone know what it means?
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
kim Joy
  • 51
  • 2
  • 3
    Possibly answered in https://stackoverflow.com/questions/7718711/javascript-triple-greater-than/7718947 – maurice Jan 08 '21 at 07:05
  • It converts the number to uint32 – Thomas Jan 08 '21 at 07:08
  • 3
    Does this answer your question? [JavaScript triple greater than](https://stackoverflow.com/questions/7718711/javascript-triple-greater-than) or [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – John Kugelman Jan 08 '21 at 07:17
  • related: https://stackoverflow.com/questions/1822350/what-is-the-javascript-operator-and-how-do-you-use-it – Rod911 Jan 08 '21 at 07:53

2 Answers2

5

>>> is called unsigned right shift (or zero fill right shift). You may have known of left/right shift. Basically it shifts the specified number of bits to the right. You can find it here

So >>>= is basically the right shift assignment.

a >>>= b

is equivalent to:

a = a >>> b
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
1

The unsigned right shift operator (a >>> b) does shift the bits of the variable a by b bits as you said.
It always returns a positive integer, so a >>> 0 would be used to make sure that the input isn't say, negative, or a string, or otherwise not a positive integer.
a >>>= b is similar to a += b, that is, it applies the right shift b to a and then assigns the output to a, similar to how a += b adds b to a and then assigns the result to a. So a >>>= b is equivalent to a = a >>> b like a += b is equivalent to a = a + b.