Thursday, September 15, 2016

Why call and apply two methods available in JavaScript

I hope everyone know about what is call and apply. Just for reminder,

The call() method calls a function with a given this value and arguments provided individually

 myFunction.call(thisArg[, arg1[, arg2[, ...]]])

The apply() method calls a function with a given this value and arguments provided as an array

 myFunction.apply(thisArg, [argsArray])

So both call and apply do similar job as to change the scope of function in which it gets executed (change this of function). So why exactly JavaScript has these 2 methods, one to pass array as an argument and another as the comma separated args. As per my experience in JavaScript I found few places where actually we can use apply but not call. May be you got some other examples also then please share. I would like to take one example here. Suppose we need to find out the min in a given array of integer (unsorted), what will be your approach? First approach we can think to search and find min or sort the array and find min. But if the question is, you have 5 numbers and find out the min of these 5 numbers, now can you think to use Math library (Math.min) in this case and find out min

 // we can pass individual numbers comma separated in Math.min and find out min easily
 Math.min(4,1,8,3,7) // 1

Now think about using array here.......??? can we pass array in this Math.min ? ..... Yes we can !

 var ar = [4,1,8,3,7];
 Math.min.apply(undefined, ar) // 1

Now suppose if only call is available in javascript we can not achieve this using call

In ES6 there is one more way to achieve this. Spread/rest parameter

 var ar = [4,1,8,3,7];
 Math.min(...ar) // 1
Know more about spread/rest parameter