← Back toFront-end tips

Pass an array as function arguments

Written byPhuoc Nguyen
Created
03 Mar, 2021
Category
Tip
Tags
JavaScript
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.
js
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:
js
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.
js
const max = (arr) => arr.reduce((a, b) => Math.max(a, b));
max([1, 2, 3, 4]); // 4

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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