Skip to content

Call and apply in JavaScript

  • by

In JavaScript, call() and apply() are both methods available on function objects. They allow you to invoke a function and explicitly specify the value of this within the function body. Additionally, they enable you to pass arguments to the function in different ways.

call() method: This method invokes a function, setting the this value explicitly and passing arguments individually.

functionName.call(thisArg, arg1, arg2, ...)
  • functionName: The function to be invoked.
  • thisArg: The value to be passed as this to the function.
  • arg1, arg2, etc.: Optional arguments to be passed individually to the function.

apply() method: This method is similar to call(), but it accepts arguments as an array or an array-like object.

functionName.apply(thisArg, [argsArray])
  • functionName: The function to be invoked.
  • thisArg: The value to be passed as this to the function.
  • argsArray: An array or an array-like object containing the arguments to be passed to the function.

Note: The call() and apply() are methods that exist on function objects, so you need to have a function to use them.

Call and apply in JavaScript example

Simple example code.

function greet(message, punctuation) {
  console.log(`${message}, ${this.name}${punctuation}`);
}

const person = { name: 'John' };

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

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

Output:

Call and apply in JavaScript

In this example, the greet() function is invoked twice. The first invocation uses call() with the person object as the this value and passes individual arguments 'Hello' and '!'. The second invocation uses apply() with the person object as the this value and passes the arguments as an array ['Hi', '?'].

What is the difference between call and apply in JavaScript?

Answer: The main difference between call() and apply() in JavaScript lies in how arguments are passed to the function being invoked.

Here’s a tabular comparison of the differences between call() and apply() in JavaScript:

call() methodapply() method
Accepts arguments as individual argumentsAccepts arguments as an array or array-like object
Arguments are passed using commasArguments are passed as an array
Example:Example:
functionName.call(thisArg, arg1, arg2, ...)functionName.apply(thisArg, [argsArray])

Here’s an example that demonstrates the difference:

function multiply(a, b) {
  console.log(a * b);
}

multiply.call(null, 5, 3);
// Output: 15

multiply.apply(null, [7, 2]);
// Output: 14

In this example, we have a multiply() function that multiplies two numbers. We invoke the function using both call() and apply().

Do comment if you have any doubts or suggestions on this Js coding.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading