Member-only story
Mastering JavaScript’s apply
Method: Clever Real-Time Use Cases You Need to Know
The apply
method call the method immediately with the context provided and arguments as array
Consider the below example
function getGreetings(greet1, greet2) {
return greet1 + ' ' + this.firstName + ' ' + this.lastName + ' ' + greet2;
}
const user = { firstName: 'Vinodh', lastName: 'Thangavel' };
const user1 = { firstName: 'Prasanth', lastName: 'Rajendran' };
console.log(getGreetings.apply(user,['Welcome',':)']))
// Welcome Vinodh Thangavel :)
console.log(getGreetings.apply(user1,['Hello',':D']))
// Hello Prasanth Rajendran :D
We have a function and return value is framed with the arguments and this value
Normal function can be called with arguments, whereas when using apply method, we will be able to pass thisValue
and arguments as array
Syntax
functionName.apply(thisValue, arguments[]);
As you see in the example, the same function provides different values based on change of thisValue
(user1
and user2
) and arguments
Whatever we pass as a first argument, that will become the this value inside that function at that point of time.
The second argument would be an array, but getGreetings
expecting as individual comma separated arguments, not array,
Apply method converts the array to individual arguments, this is a very useful feature.