Pass an array as function arguments
JavaScript has some built-in functions that accept a list of individuals arguments, but passing an array doen't work. `Math.max`
, `Math.min`
are some of them.
Math.max(1, 2, 3, 4);
Math.max([1, 2, 3, 4]);
If we want to pass a dynamic array of numbers, then the ES6 spread operator (`...`
) can help. It turns a varible to a list of individual parameters:
const array = [1, 2, 3, 4];
Math.max(...array);
JavaScript engines implemented by different browsers have the limited number of parameters. Using the `...`
operator doesn't work if you have a big array. Using the `reduce`
method doesn't have this problem.
const max = (arr) => arr.reduce((a, b) => Math.max(a, b));
max([1, 2, 3, 4]);
See also