0

I found an implementation of javascript forEach loop and one thing bothers me.

if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function") {
        throw new TypeError();
    }

    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in this) {
            fun.call(thisp, this[i], i, this);
        }
    }
};
}

What is the point of unsigned right shift this.length >>> 0?

mwende
  • 36
  • 1
  • 3

1 Answers1

1

It's a way to ensure that len is a an 32 bits unsigned integer.

By using >>> 0 you can never get NaN or negative values.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
  • This makes sense. I was thinking for a while what if there is somehow a negative value and the output will be a huge number, but then I found out that the next statement ```if (i in this)``` prevents the error of non-existing index in array. Thanks! – mwende Apr 15 '20 at 09:35