Javascript array.prototype.map when/why use third argument

Viewed 1908

I recently noticed that when using array.prototype.map(), my callback function may accept a third argument which is the array I'm mapping. I wonder if there are any use cases for this argument because inside the callback function, the array can be accessed anyways.

If I access the array I'm mapping inside the callback function, why/when should I rather use the third argument instead of just accessing the array?

example

Even though both methods should work fine in every use case I can imagine, I'd like to know which is the recommended way to do it and why.

3 Answers

The third argument can be useful when you are chaining several array methods and need to access the intermediate state of the array (result of the previous operation):

const source = [-3,-2,-1,0,1,2,3,4,5];
source
  .filter(n => n >= 0)
  .map((n, index, arr) => {
     // arr contains only non-negative numbers
     // here you may have some logic that rely on it
     return n;
  })

EDIT: This answer was already (coincidentally) given in the flagged dupe. Check it out over there.


You may wish to reference the original array in a generic fashion. For instance, the callback may be a separate function, not just an anonymous one as is usually seen:

function arrayMapper(val, idx, arr) {
  // Some operations which use arr
}

myArray.map(arrayMapper);
myOtherArray.map(arrayMapper);

Note how each in execution of arrayMapper, the arr parameter refers to a different array in the outer scope.

You are using normal global context where this need does not arise.See below example where you are not using arrow function (which preserve the current context) with Object oriented function programming. At that time it helps as third property. In first example, i cant access this.numbers in anonymous function as anonymous fun has its own context. Here it useful when you want to access original array for operarions

working example :

function Demo (numbers){
   this.numbers = numbers;
}

Demo.prototype.doMap = function () {
 return this.numbers.map(function(num, index, array) {
     return array[num]
  });
}

var obj  = new Demo([1, 2, 4, 2, 3]);

console.log(obj.doMap()); // will work

non working example if i don't pass array, it will throw error.

function Demo (numbers){
   this.numbers = numbers;
}

Demo.prototype.doMap = function () {
 return this.numbers.map(function(num, index, array) {
     return this.numbers[num] // cant access original number array using this (this refers to context of anonymous function)
  });
}

var obj  = new Demo([1, 2, 4, 2, 3]);

console.log(obj.doMap()); // throw error

Related