1

I just read some code: Why doesn't indexOf work on an array IE8?

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;
  };
}

I'be been writing JavaScript for years now, and i have never seen parameters handled like this before.

elt, /*, from*/

What is happening here?

Community
  • 1
  • 1
THE AMAZING
  • 1,496
  • 2
  • 16
  • 38

2 Answers2

4

Array.prototype.indexOf has a required argument searchElement and an optional one fromIndex.

Usually the length property shouldn't count optional arguments, but if the polyfill used function(elt, from) then the length would be 2.

var f1 = function(a, b) {},
    f2 = function(a /*,b*/) {};
f1.length; // 2
f2.length; // 1

So my guess is that it's commented to make sure Array.prototype.indexOf.length is 1, as dictated by the spec:

The length property of the indexOf method is 1.

Note commenting it does not limit its functionality because it is still accessible through arguments[1].

It could also be remove (comments are ignored). However, having it as a comment can be helpful for authors.

Oriol
  • 274,082
  • 63
  • 437
  • 513
1

All functions in Javascript have an implicit "arguments" parameter. The commented /*from*/ isn't doing anything, but the author clearly is trying to give a heads up that you can pass another parameter to this function. You can see down below where they read the parameter: var from = Number(arguments[1]);

Here's a reference: https://github.com/iteles/Javascript-the-Good-Parts-notes#arguments

Ghazgkull
  • 970
  • 1
  • 6
  • 17