JavaScript: How To Pass An Array To Math.max?

Math.max is a very handy function in JavaScript to quickly find maximum of given numbers. The function takes a variable no. of arguments which may range from one to as much as you like.

Math.max(d1, d2, d3, ... , di);

But what would you do if you have your numbers stored in an array and you want to find maximum of them? Math.max doesn’t take array as an argument.
If you have any ideas please share below in comments. I came up with this quick hack:

Math.max.apply(Math, your_array_here);

You can try this hack on any function that takes arguments in similar manner. Enjoy!

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

Leave a Reply

Your email address will not be published. Required fields are marked *