Hackernoon logoTricks in using JavaScript Apply function by@llauderesv

Tricks in using JavaScript Apply function

Vince Llauderes Hacker Noon profile picture

@llauderesvVince Llauderes

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

Math.max(5,2,1,3,4) // Outputs 5. 

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

const list = [5,2,1,3,4];

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:

function max(array) {
return Math.max.apply(Math, array);
function min(array) {
return Math.min.apply(Math, array);
max([5,2,1,3,4]); // Outputs 5
min([5,2,1,3,4]); // Outputs 1

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


Join Hacker Noon

Create your free account to unlock your custom reading experience.