DEV Community

Cover image for Function Call and Apply Methods
Bello Osagie
Bello Osagie

Posted on • Updated on

Function Call and Apply Methods


call() Method

The call() method accepts an object and optionally argument list.

See the syntax below:

object.method.call(obj1[, arg1, ...argN])
Enter fullscreen mode Exit fullscreen mode

call() method with a parameter object

The call() method is used on an object. The parameter passed to the function is also an object.

See the examples below:

Without call() method.

const person = {
  firstName: "Osagie",
  lastName: "Bello",
  fullName() {
    return `Hello ${this.lastName} ${this.firstName}!`;
  }
};

console.log(person.fullName()); // Hello Bello Osagie!
Enter fullscreen mode Exit fullscreen mode


With call() method.

const person = {
  fullName() {
    return `Hello ${this.lastName} ${this.firstName}!`;
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.call(person1)); Hello Bello Osagie!
console.log(person.fullName.call(person2));  // Hello Richard Jury!
Enter fullscreen mode Exit fullscreen mode

call() method with arguments

The call() method is used on an object with arguments also passed to the function.

const person = {
  fullName(country, city) {
    return `${this.firstName} ${this.lastName}, ${country} ${city}`;
  }
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.call(person1, "Nigeria", "Lagos"));  
// Osagie Bello, Nigeria Lagos
console.log(person.fullName.call(person2, "UK", "Oxford"));  
// Richard Jury, UK Oxford
Enter fullscreen mode Exit fullscreen mode

apply() Method

The apply() method accepts an object and optionally array instead of an argument list.

See the syntax below:

object.method.apply(obj1[, array])
Enter fullscreen mode Exit fullscreen mode

apply() method with arguments array

Not only an object be passed to the apply method, but it also accepts an array.

const person = {
  fullName(country, city) {
    return `${this.firstName} ${this.lastName}, ${country} ${city}`;
  }
};

const person1 = {
  firstName: "Osagie",
  lastName: "Bello"
};

const person2 = {
  firstName: "Richard",
  lastName: "Jury"
};

console.log(person.fullName.call(person1, "Nigeria", "Lagos"));  
// Osagie Bello, Nigeria Lagos

console.log(person.fullName.apply(person2, ["UK", "Oxford"]));  
// Richard Jury, UK Oxford
Enter fullscreen mode Exit fullscreen mode

Happy coding!!!


image.png


image.png

Top comments (0)