Passing Arrays as Function Arguments

Samantha Ming
DailyJS
Published in
4 min readFeb 18, 2019

--

If you want to pass an array into a variadic function. You can use ES6 spread to turn that array into a list of arguments. Yay, so much cleaner and no useless null from the old apply way 👏

function sandwich(a, b, c) { 
console.log(a) // '🍞'
console.log(b) // '🥬'
console.log(c) // '🥓'
}
const food = ['🍞', '🥬', '🥓'];// Old way
sandwich.apply(null, food);
// ✅ ES6 way
sandwich(...food);

Using it with Math functions

The ability to turn an array into a list of arguments is super handy with the Math functions.

Example: Find the Largest Number

Let’s say you want to find the largest number using the Math.max() function.

const largest = Math.max(5, 7, 3, 4);console.log(largest); // 7

But rarely, would you pass in individual values. More likely, you would want to find the maximum element in an array. So the question now is, how do you pass an array of values into a function that accepts individual arguments and NOT an array?

This would be terrible:

const numbers = [5, 7, 3];// 🤮 Yuck!
Math.max(numbers[0]…

--

--

Samantha Ming
DailyJS

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛