1

I was looking at this function Array.prototype.find from (mdn polyfill):

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

i don't understand the goal of this code:

var length = list.length >>> 0;
gontard
  • 28,720
  • 11
  • 94
  • 117
  • 1
    @RGraham -- not a dupe (at least not of that question). The other question is asking what the op is. This one is asking "why the hell would you use it here?" :) –  Jul 23 '15 at 07:19
  • 2
    @zyklus The answer in the duplicate answers that too – CodingIntrigue Jul 23 '15 at 07:20

2 Answers2

3

x >>> 0 forces x to become an integer. Thus, if list is an array, length shall be its length; but if .length doesn't exist, or is something silly like {a: 17, length: "Unicorns"}, length will be 0.

Amadan
  • 191,408
  • 23
  • 240
  • 301
2

There is an implicit "cast to int" inherent in any javascript binary ops. So 3.14159 >>> 0 === 3, and any invalid values, like 'foo' get cast to 0

Why >>> instead of >> or |? Apparently they're expecting huge arrays (but not too huge):

Math.pow(2,31)>>0
-2147483648

Math.pow(2,31)>>>0
2147483648