3

Reading documentation for a few years I've often been confused by the syntax commonly used in explaining function signatures. for instance:

From the Mozilla Array.map Docs:

var new_array = arr.map(callback[, thisArg])

The docs list three arguments for the callback: currentValue, index, and array, but the signature just has this weird callback[, thisArg] syntax. Whats the deal with that comma? why are there array brackets next to 'callback'? Is there any documentation out there on this syntax? is there a name for this syntax? any help would be appreciated.

Thanks!

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
sunnyharris
  • 115
  • 1
  • 1
  • 6

2 Answers2

1

The function Array.prototype.map expects a function as the first argument:

var new_array = arr.map(callback[, thisArg])

The square brackets indicate that the secondparameter is optional. You can call Array.prototype.map with or without a second argument. Both functions calls are valid:

var array = [1, 2, 3, 4];

var myFunc = function (number) {
  return number * 5;
};

var myFuncUsingThis = function (number) {
  console.log(this);
  return number;
};

var myThisArg = {
  foo: 'bar'
};

console.log(array.map(myFunc));
console.log(array.map(myFuncUsingThis, myThisArg));

The last is the same as

console.log(array.map(myFuncUsingThis.bind(myThisArg)));

So, if the function that you provide to Array.prototype.map uses the this object, you can specify the this object of the function when it is called by Array.prototype.map by using the second (optional) argument.


currentValue, index and array are something completely different. You do not have to provide them when you call Array.prototype.map. Instead, Array.prototype.map provides them for you: it calls the function that you gave it with those three arguments (but you don't have to use all three arguments).

The first argument to your function is the value of the element in the array that is currently processed, the second argument is the index of that element, and the third argument is the array itself.

You can write a function that takes use of the index parameter:

var array = Array(20).fill(0); // an array containing 20 zeros

var evenNumbers = array.map(function (number, index) {
  // number is zero, index is the index of the element we should transform
  return index * 2;
});

console.log(evenNumbers);

Maybe it helps if you take a look at a (naïve) implementation of Array.prototype.map:

Array.prototype.map = function (callback, thisArg) {
  // "this" is the array on which we work

  var arr = []; // the new array that we build
  var result;
  for (var i = 0; i < this.length; i += 1; i++) {
    result = callback.call(thisArg, this[i], i, this);
    arr[i] = result;
  }
  return arr;
};
PeterMader
  • 6,987
  • 1
  • 21
  • 31
0

The parameters inside the brackets mean they are optional.

Saravana
  • 37,852
  • 18
  • 100
  • 108