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();
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);
sayHello.apply(person);
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)
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);
console.log(maxNum);
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.