Difference Between

.call() and .apply()

In JavaScript, both call and apply are methods used to invoke functions and set the this context explicitly to an object different from the current context. However, they differ in how they handle function arguments.

The call Method

The call method invokes a function with a given this value and arguments provided individually. This is particularly useful when you know the number of arguments that the function expects. It allows you to invoke a function as if it were a method of a particular object, even if it's not.

Syntax:

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

For example, if we have a function that adds two numbers and logs the result, we can use call to invoke it with a specific context:

function add(a, b) {
  console.log(this.description + (a + b));
}
 
const obj = {
  description: "The sum is: "
}
 
add.call(obj, 5, 3); // Outputs: "The sum is: 8"

The apply Method

The apply method is similar to call but instead of taking arguments individually, it takes an array of arguments. This makes apply very handy when you don't know in advance how many arguments will be passed to the function, or when the arguments are already in an array or array-like object.

Syntax:

function.apply(thisArg, [argsArray]);

Using the same example as above, we can use apply like this:

function add(a, b) {
  console.log(this.description + (a + b));
}
 
const obj = {
  description: "The sum is: "
}
 
add.apply(obj, [5, 3]); // Output: "The sum is: 8";

Key Differences

  • Argument Handling: call takes an argument list, whereas apply takes a single array of arguments. This distinction is crucial when you are working with functions where the number of parameters isn't fixed or they are naturally collected in an array.
  • Performance: Historically, call has generally been slightly faster than apply, particularly when dealing with functions that accept a large number of arguments. However, with modern JavaScript engines, this difference is often negligible.

Use Case Example:

If you are implementing a function like Math.max which does not inherently handle array inputs to find the maximum number, you can elegantly use apply to pass an array directly:

const numbers = [1, 2, 3, 4, 5];
const max = Math.max.apply(null, numbers); // Returns 5
Last Update: 18:03 - 18 April 2024

On this page