Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use /*, */ around arguments and why use >>> when extracting the length of an array? [duplicate]

Tags:

javascript

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;).

like image 616
Egil Hansen Avatar asked Sep 06 '09 11:09

Egil Hansen


1 Answers

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

like image 128
pjp Avatar answered Sep 21 '22 22:09

pjp