Problem
You want to map values of an array to function parameters in ES5.
Ingredients
- 1 function
- 1 array
- the
apply()
method
Directions
-
Given: a function that takes different parameters and an array containing concrete arguments.
function add(x, y, z) { return x + y + z; } var parameters = [2, 3, 4];
-
Naive solution, but also very verbose: access array values by index.
var result = add( parameters[0], parameters[1], parameters[2] ); console.log(result); // 9
-
Better to use the
apply()
method (at least when you are in ES5).... var parameters = [2, 3, 4]; var result = add.apply(null, parameters); console.log(result); // 9
- Voilá, there you got a perfect mapping from array values to function parameters.
Alternative recipes
-
Since ES2015: use the spread operator, which can be used to map array values to function parameters:
... let parameters = [2, 3, 4]; let result = add(...parameters); console.log(result); // 9