JavaScript apply() Function Tutorial

In this section, we will learn what the apply() function is and how to use it in JavaScript.

What is JavaScript apply() Function?

The `apply()` method works pretty much the same as the `call()` method. Basically, just like the `call()` method, when we want to explicitly bind the `this` keyword inside a function to a specific object, we can use the `apply()` method as well.

JavaScript apply() Function Syntax:

object.apply(object, args…);

apply() Function Parameters:

The `apply` method takes multiple arguments. But the first argument should be the name of the object in which we want to bind the `this` keyword of the target function to that object.

Also, the rest of arguments that we set for this method are actually the arguments we want to set for the target function.

apply() Function Return Value:

The return value of the apply() method is the same as the function that invoked this method.

Example: using apply() function in JavaScript

const obj = {
  firstName: "John",
  lastName : "Doe"
}
function changeName(name , lastName){
  this.firstName = name;
  this.lastName = lastName;
}
changeName.apply(obj, ["Omid","Dehghan"]);
console.log(obj.firstName, obj.lastName);

Output:

Omid Dehghan

As you can see, the second argument to the `apply()` method is an array of two elements. So the first element will be assigned to the first parameter of the `changeName` function and the second element will be assigned to the second parameter of the function.

Note: please check the array section if you’re not familiar with arrays.

JavaScript apply vs call methods

The `apply()` method is capable of taking an array as its second argument and assigns each of the elements of the array to each parameter of the target function.

Note: the first argument is the name of the object that wants to be bound to the `this` keyword in the target function.

But we can’t pass an array as the second argument to a call() method and expect each element of that array to be assigned to the parameters of the target function. Basically, if we set an array as the second argument of the call() method, that array with all the elements it has will be assigned as the second argument of the target function.

More to Read:

JavaScript call() function tutorial 

JavaScript bind() function tutorial 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies