65.9K
CodeProject is changing. Read more.
Home

Difference Between .call() and .apply() in Javascript

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (7 votes)

Oct 7, 2014

CPOL

1 min read

viewsIcon

12511

Introduction There is always a confusion in .call() and .apply(). Where to use when? Why we need to call a function using .call() and .apply(),  even if, we can directly call that function ? For Instance :someFunction.call() and someFunc.apply() But we can directly call the function by someFunction(

Introduction

There is always a confusion in .call() and .apply(). Where to use when?
Why we need to call a function using .call() and .apply(),  even if, we can directly call that function ?

For Instance :someFunction.call() and someFunc.apply()
But we can directly call the function by someFunction().
Because JavaScript functions rely on their scope.

var person = {name: 'Mac', age: 25};

var sayHello = function() {
                   alert('Hello, ' + this.name);
               }

In the above code, if we call the function directly.

sayHello(); // it will give you unexpected result

Again if ‘strict mode’ is on then it will give you an error…

TypeError: this is undefined

But if we call like…

sayHello.call(person); //Hello,Mac
sayHello.apply(person); //Hello,Mac

Lets have a look on the difference

.call()

It calls a function with given values and arguments provided individually

  • It takes the parameter as comma separated.
  • It looks like :- testfunction.call(valueForThis, arg1, arg2, ...);

Tip : When To use .call() – When you know the number of arguments to be passed.
Example :

var maxNum = Math.max.call(null, 45, 34, 23, 109, 345, 567);
document.write(maxNum)​ // output is 567

Advantage : when we call a function with out argument or fixed argument.

.apply()

  • It calls a function with given values and arguments provided as an array or array object.
  • It  takes the argument for this value and an array of object, basically apply expects its 2nd  argument as an array.
  • It looks like :- testfunction.apply(valueForThis, [arrayOfArgs]);

Tip : When To use .apply() – When you don’t know the number of arguments to be passed to that function.
Example :

var numarr = [45, 34, 23, 109, 345, 567];
var maxNum = Math.max.apply(null, numarr); //second argument expecting an array
console.log(maxNum); // output is 567

Advantage: We are getting an advantage of using .apply() because here we don’t need to check the number of arguments to call a function.

Conclusion

Both these have their pros and cons so their should no confusion what to use when while using.