user3591425
user3591425

Reputation:

How do these extra parameters work with map()?

I'm working on better understanding functional programming in javascript, but I'm a bit confused by what I've seen fed to map functions. Take the example below:

const f = x => (a, b, c) => b + a;

const arr = [1, 2, 3, 4, 5, 6];

const m = arr.map(f(1));

document.write(m);

When f returns a it will print each value, as expected. If it returns b it seems to return the index, and c will return the entire array for each value. Is there a reason to why this function works this way?

Upvotes: 1

Views: 76

Answers (2)

Damon
Damon

Reputation: 4336

In your example, You are invoking map with a 3-ary callback where:
a -> current element
b -> current index
c -> original array

and returning c. Therefore, your result will be a new array containing a reference to the original array for every element iterated over.

Since you aren't doing anything with x, there is no need for a nested function here. A better example of how you can use this concept would be something like:

const add = a => b => a + b

const arr = [1, 2, 3, 4]

const newArr = arr.map(add(3))
// [4, 5, 6, 7]
console.log(newArr)

Upvotes: 3

guest271314
guest271314

Reputation: 1

Array.prototype.map() callback function has three default parameters

  1. The current element of the iteration
  2. The index of the current element of the iteration
  3. The array that .map() function was called upon

f returns a function which is set as callback of .map()

See also Array.from()

Upvotes: 3

Related Questions