JavaScript call() Method vs apply() Method

JavaScript, like other programming languages, offers flexibility and multiple approaches for handling the "this" keyword and function arguments. Among these techniques, the call and apply methods are commonly employed. Both methods enable the invocation of a function with arguments and allow the specification of the "this" value, albeit with subtle distinctions in their implementations. This article aims to elucidate the variances between these two methods through theoretical explanations and practical illustrations for enhanced comprehension and learning.

call Method

The call function is utilized to invoke a function with a specific this value and separate arguments provided. This method is beneficial when the number of arguments that need to be sent is predetermined.

Syntax:

Example

function.call(thisArg, arg1, arg2, ...);

Example

Example

// Define a simple function to greet a person  

function greet(greeting, punctuation) {  

    console.log(greeting + ', ' + this.name + punctuation);  

}  

  // Create an object with a name property  

let person = {  

    name: 'Tom'  

};  

// Use the call() method to invoke the greet function  

greet.call(person, 'Hello', '!');

Output:

Output

Hello, Tom!

Explanation:

  • The greeting and punctuation are the two inputs that the greet function accepts.
  • The name property of the object person we construct is set to 'Tom'.
  • We call the greet function by supplying 'Hello' and '!' as parameters and setting this context to the person object using the call method.
  • The result is Hello, Tom!
  • apply Method

Just like the call method, apply function can also receive arguments in the form of an array or an array-like object. This functionality is beneficial when you need to pass an array of arguments to a function.

Syntax:

Example

function.apply(thisArg, [argsArray]);

Example

Example

// Define a simple function to greet a person  

function greet(greeting, punctuation) {  

    console.log(greeting + ', ' + this.name + punctuation);  

}  

// Create an object with a name property  

let person = {  

    name: 'Abraham'  

};  

// Use the apply() method to invoke the greet function  

greet.apply(person, ['Hi', '!!']);

Output:

Output

Hi, Abraham!!

Explanation :

  • As before, the greet function accepts two arguments: greeting and punctuation.
  • We construct an object person and give it the name property value "Abraham."
  • We call the greet function by giving ['Hi', '!!'] as an array of parameters and adding this context to the person object using the apply method.
  • The result is Hi, Abraham!!
  • Difference between call and apply Methods

The call and apply methods are Function methods in JavaScript that call a function and set the value of that function to this . They both successfully pass the value of this to your specified value and call a function, where they differ in how they pass arguments. Let us look at those differences.

  1. Purpose
  • The call and apply, both are utilized to request a function with a certain this value or context.
  • They give you the control to find the value which this keyword is using to request a function, guaranteeing the function is called with the appropriate potential context at the time of running.
  1. Argument Passing
  • The call method passes arguments as individual values after this value.
  • The applymethod passes arguments as an array or array-like object after this value.
  1. Performance
  • The call may be slightly more efficient for a small, fixed number of arguments because it does not require array
  • The apply might introduce some performance overhead when dealing with large arrays, as it expects the arguments into an array.
  1. Flexibility
  • The call is less flexible in cases where you have a variable number of arguments, as you need to pass each one individually.
  • The apply is more flexible when working with an array of arguments.
  1. Use Cases
  • The call is suitable when you know the exact number of arguments and you want to pass them individually
  • The apply is suitable when you have an array of arguments or the number of arguments is dynamic.
  • Practical Examples

Exploring a wider range of diverse examples can enhance our comprehension of the functionalities and benefits of the call and apply methods. While both techniques serve the purpose of invoking a function with a defined this context, they vary in their approach to passing arguments.

1. Invoking a Function with Different this Contexts

We possess two objects, person1 and person2, each containing distinct name properties. We shall employ the call and apply methods to invoke a method from person1 and apply it to person2.

Using call

Example

Example

const person1 = {

    name: 'Abraham',

    greet: function(greeting, punctuation) {

        console.log(greeting + ' ' + this.name + punctuation);

    }

};

const person2 = {

    name: 'Tom'

};

person1.greet.call(person2, 'Hello', '!');

Output:

Output

Hello Tom!

Explanation:

The call method is employed to invoke the greet function of person1, while setting the context to person2. The arguments ('Hello' and '!') are then passed separately following this context switch.

Using apply

Example

Example

const person1 = {

    name: 'Abraham',

    greet: function(greeting, punctuation) {

        console.log(greeting + ' ' + this.name + punctuation);

    }

};

const person2 = {

    name: 'Tom'

};

person1.greet.apply(person2, ['Hello', '!']);

Output:

Output

Hello Tom!

Explanation:

The apply function is employed to invoke the greet method of person1, but this time the context is switched to person2. The parameters are provided in an array (['Hello', '!']), which are then spread and forwarded to the method.

2. Using Arguments Dynamically

Let's create a function that computes the total of a set of numbers. We'll make use of the call and apply methods to pass the numbers in various manners.

Using call

Example

Example

function sum() {

    let total = 0;

    for(let i = 0; i < arguments.length; i++) {

        total += arguments [i];

    }

    return total;

}

console.log(sum.call(null, 10, 20, 30, 40, 50));

Output:

Explanation:

The call function sends the numbers one by one as parameters to the sum function. The arguments object, which acts like an array within the function, allows us to iterate through it and compute the total sum.

Using apply

Example

Example

function sum() {

    let total = 0;

    for(let i = 0; i < arguments.length; i++) {

        total += arguments[i];

    }

    return total;

}

const numbers = [10, 20, 30, 40, 50];

console.log(sum.apply (null, numbers));

Output:

Explanation:

The apply method is employed to invoke the sum function with its context set to null. Within apply, the array of numbers is provided as a singular argument and then deconstructed within the function as separate arguments.

3. Formatting of Full Name

A function can be created with a specific name and then invoked using call or apply methods, adjusting the prefix and suffix as needed.

Using call

Example

Example

function getFullName(prefix, suffix) {

  return `${prefix} ${this.firstName} ${this.lastName} ${suffix}`;

}

const userA = { firstName: "Tom", lastName: "Cruise" };

const userB = { firstName: "Taylor", lastName: "Swift" };

const name1 = getFullName.call(userA, "Mr.", "Sr.");

console.log(name1);

Output:

Output

Mr. Tom Cruise Sr.

Explanation:

The call function is utilized to invoke the getFullName function, enabling access to the prefix and suffix values' patterns for retrieval. It determines which name to output by passing it to the console after the selection process.

Using apply

Example

Example

function getFullName(prefix, suffix) {

  return `${prefix} ${this.firstName} ${this.lastName} ${suffix}`;

}

const userA = { firstName: "Tom", lastName: "Cruise" };

const userB = { firstName: "Taylor", lastName: "Swift" };

const name2 = getFullName.apply(userB, ["Ms.", "Jr."]);

console.log(name2);

Output:

Output

Ms. Taylor Swift Jr.

Explanation:

The apply function is utilized to invoke the getFullName function, enabling access to the prefix and suffix values' patterns for retrieval. It determines which name to display by passing this information to the console after processing.

Comparative Tabular Representation of call vs apply Method

Below is a table illustrating a comparison between the call and apply functions:

Feature call() apply()
Usage Call a function with the specifiedthisvalue. Call a function with the specifiedthisvalue.
Arguments Arguments are passed individually to the program. Arguments are passed as an array or array-like object.
Syntax func.call (thisArg, arg1, arg2, …) func.apply (thisArg, [arg1, arg2, …])
Flexibility It is less flexible with variable arguments. It is more flexible with dynamic arguments.
Example greet.call (person, "Hello", "John") greet.apply (person, ["Hello", "John" ])
Context (this) thisis set to the first argument (thisArg) thisis set to the first argument (thisArg)
Array of Arguments No, you have to pass arguments one by one. Yes, arguments must be passed as a combined array.
Performance It is generally faster to use fewer arguments. It is less efficient for large arrays due to array handling.
Common Use Cases When you know the exact number of arguments. When arguments are dynamically generated or already in an array.

Conclusion

The call and apply methods in JavaScript are valuable tools for invoking functions with specific arguments and context. The key contrast lies in how arguments are passed to these methods: individually for call and as an array for apply. Understanding and recognizing these disparities, as well as determining when to utilize each method, can enhance your ability to create code that is more adaptable and can be reused efficiently.

In summary:

  • When passing arguments individually and knowing the quantity to pass, utilize the call method.
  • In cases where arguments are contained in an array or when the number of arguments is variable, opt for the apply method.

The call and apply functions in JavaScript are essential for enhancing flexibility, reusability, and maintainability in code. They empower developers to have fine-grained control over the context (this) in functions and the arguments being passed.

Frequently Asked Questions (FAQs)

  1. Can you explain the significance of call and apply methods in JavaScript?

Both call and apply are used to invoke a function with a specific this context which means, to change the value of this inside the function. This is useful when you want a function defined in one object to be used in another object.

  1. When should I use call vs apply?
  • You can use call when you already have the arguments separately.
  • You can use apply when your arguments are already in an array or array-like object like the arguments object or Nodelist.
  1. Can I use them with methods inside objects?

Indeed, they are particularly beneficial for leveraging methods from one object and implementing them in another.

Example

Example

const person1 = {

  fullName: function () {

    return this.firstName + " " + this.lastName;

  }

};

const person2 = {

  firstName: "John",

  lastName: "Doe"

};

console.log (person1.fullName.call (person2));

Output:

Output

John Doe
  1. Are there any contemporary replacements for the functions call and apply?

Certainly. In modern code, the spread operator (…) can be employed with call or directly, as an alternative to using apply.

Example

func.call(null, ...args); // similar to apply(null, args)

In addition, to establish a lasting connection, the bind method can be employed.

Is there still relevance in the present day for call and apply?

Indeed, even with the introduction of the spread operator in ES6, call and apply remain essential for managing context (this) in JavaScript and are valuable in various scenarios, particularly in object-oriented and functional programming.

Are there return values from call and apply?

Certainly. The return values of call and apply are identical to what the functions themselves return when called normally.

The sole distinction lies in the manner in which you provide the arguments to the function:

Method Syntax Example How Arguments are Passed
call() func.call (thisArg, arg1, arg2, …) Passed one by one
apply() func.apply (this.Arg, [arg1, arg2, …]) Passed as an array

Input Required

This code uses input(). Please provide values below: