Using multi-arg JavaScript functions with map()

Panu Viljamaa
Mar 31 · 1 min read
function times (x, i, a, y=this)
{ return x * y;
}
let [ten, twenty, thirty]
= [1, 2, 3].map (times, 10);
let tenB = times.call(10, 1);

The arguments ‘i’ and ‘a’ are never used, but need to be there because map() passes them in. The argument ‘y’ is not passed in by map() but map() makes its second argument to be the ‘this’ inside the function being mapped over. Since we are using ES6 default-argument-value “y=this”, the 2nd argument we pass to map, 10, will show up as the y inside the function.

What if your function takes more than two “real”arguments, say x, y and z? You can use array destructuring to make such a function callable also by map, like this:

function manyArgs (x, i, a, [y, z]=this)
{ return x * y * z;
}
[1,2,3] .map (manyArgs, [2,3] ); // == [6, 12, 18]
Panu Viljamaa

Written by

Class Cloud LLC