← Back toFront-end Tips

Pass an array as function arguments

Written byPhuoc Nguyen
03 Mar, 2021
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.
They are used to find the biggest and smallest numbers in the passed arguments, repectively.
Math.max(1, 2, 3, 4); // 4

// Doesn't work because it treats the array as a single parameter
// That parameter isn't a number, so the function returns `NaN`
Math.max([1, 2, 3, 4]); // NaN
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); // 4
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]); // 4

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn