Reputation:
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
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
Reputation: 1
Array.prototype.map()
callback function has three default parameters
.map()
function was called uponf
returns a function which is set as callback
of .map()
See also Array.from()
Upvotes: 3