4

Possible Duplicate:
What is the JavaScript >>> operator and how do you use it?

Mozilla's Array.prototype.map(), described in the Javascript 1.5 documentation, is implemented with the following:

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

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

    return res;
  };
}

The line I'm struggling to understand is:

var len = this.length >>> 0;

Mozilla's Js 1.5 bit-wise operator reference, explains that >>> is the bitwise operator Zero-fill right shift.

Zero-fill right shift

Shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Does this provide some kind of safety that returning array.length does not, or is this some kind of type coercion?

Community
  • 1
  • 1
Bayard Randel
  • 9,930
  • 3
  • 42
  • 46
  • possible duplicate of [What is the JavaScript >>> operator and how do you use it?](http://stackoverflow.com/questions/1822350/what-is-the-javascript-operator-and-how-do-you-use-it) (that question asks about the exact same line of code. It also leads to more exact duplicates.) – sth Jul 27 '10 at 22:13
  • array.length is already an integer, and >>> always results in an integer. (null>>>0)===0, ("blargh">>>0)===0, (undefined>>>0)===0... I do not see why the line of code is necessary either. – Warty Jul 27 '10 at 22:14
  • Maybe it's if either the length property is redefined on Array or more likely, so that the function can be called on other array like objects – Russ Cam Jul 27 '10 at 22:16
  • 1
    In particular the ECMAScript standard requires that `Array.prototype.map` be applicable to other array-like objects. On array-likes that are not Array instances, it is possible to set the `length` property to a non-integer. The ECMAScript standard, being a standard, defines what exactly should happen when you do something crazy like this, and Mozilla are simply replicating what the spec says should happen in this unlikely corner case. – bobince Jul 27 '10 at 22:34

0 Answers0