Tricks in using JavaScript Apply function

Vince Llauderes
HackerNoon.com
2 min readAug 23, 2018

--

Did you ever feel cumbersome when you use the built in JavaScript Functions Math.max and Math.min?

Image from google.com

We already know that this two built functions accepts a variable argument-list. For instance when using the Math.max to get the highest value it may be written in this way

Works pretty well. How about if we’re dealing with array of values we might write our code in this way.

What’s wrong in this Implementation?

I guess you know what’s wrong in this. As you may notice this implementation is not flexible. What if the size of array grows? We add more values in Math.max argument. As a developer we didn’t want to do that we do hard code the values. Unless we know the size of array are we dealing with.

How do we fix this problem? Apply function to the rescue.

So we will use the Apply function to supply a variable arguments in Math.max and Math.min

For instance:

This is equivalent to what we did before but now we’re using a built in JavaScript apply function. The value that we pass in the argument transform into comma separated value for instance: ([5,2,1,3,4] -> 5,2,1,3,4).

Now our Math.max and Math.min is now flexible it can now handle a large array of values without getting worried in it.

Hope it Helps ^_^

Follow me on twitter https://twitter.com/llaudevc

--

--