6

I was looking in the javascript reference manual on the indexOf page at developer.mozilla.org site, and noticed a few things in their implementation code of indexOf, I hope somebody can explain to me.

To save everybody a round trip to the mozilla site, here is the entire function:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

What I do not understand is the /*, from*/ in the function declaration, and the zero-fill right shift >>> in the extracting of the length of the array (var len = this.length >>> 0;).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Egil Hansen
  • 15,028
  • 8
  • 37
  • 54

3 Answers3

10

The /*, from */ is a commented out parameter. However it looks like it has been left in the comments to show that this parameter can optionally be specified for the function.

var from = Number(arguments[1]) || 0;

I believe that arguments[1] would be the from value if passed in.

The arguments array is especially useful with functions that can be called with a variable number of arguments, or with more arguments than they were formally declared to accept. http://www.devguru.com/Technologies/Ecmascript/Quickref/arguments.html

The >>> is an unsigned right shift. It's being used here to convert a potentially signed number length into an unsigned number.

Extract from Professional JavaScript for Web Developers

http://www.c-point.com/javascript_tutorial/jsoprurshift.htm

pjp
  • 17,039
  • 6
  • 33
  • 58
  • Thanks, makes sense now. I did not realize that the length property could be anything but unsigned, javascript puzzles me at times :) – Egil Hansen Sep 06 '09 at 14:06
3

The /*, from */ is an optional parameter. Notice var from = Number(arguments[1]) || 0; after that. If a second parameter was passed in the function call, the variable from will set to it.

Not sure about the unsigned right shift. Doesn't make any sense to me.

Ammar
  • 1,148
  • 9
  • 15
3

The /*, from*/ in the function declaration is just a comment by the author to say, that there’s a second optional parameter named from. It’s wrote as a comment so that it isn’t part of the signature (Array.prototype.indexOf.length returns 1).

And the right shift is probably used to always get an integer value of this.length.

Gumbo
  • 643,351
  • 109
  • 780
  • 844