Curriculum Series

What is the difference between call( ) and apply( )?

What is the difference between call( ) and apply( )?

What is the difference between call( ) and apply( )?

JavaScript

call( ) vs apply( )

Both call( ) and apply( ) are methods that allow you to execute a function with a specified 'this' context and arguments. They enable you to control what the 'this' keyword refers to inside the function being called.

Here's an example to demonstrate this:

JAVASCRIPT
1const person = {
2 name: 'John',
3 greet: function () {
4 return `Hello, ${this.name}`;
5 },
6};
7
8const manager = {
9 name: 'Sarah',
10};
11
12// Using the greet function with manager's context
13person.greet.call(manager); // Returns: "Hello, Sarah"
14person.greet.apply(manager); // Returns: "Hello, Sarah"

The difference between call and apply

The main difference between call() and apply() is how they handle the arguments:

  • call( ) accepts arguments individually, functionName.call(thisContext, arg1, arg2).
  • apply( ) accepts arguments as an array, functionName.apply(thisContext, [arg1, arg2]).
JAVASCRIPT
1const person = {
2 name: 'John',
3 introduce: function (role, department) {
4 return `Hello, I'm ${this.name}, ${role} in ${department}`;
5 },
6};
7
8const employee = {
9 name: 'Sarah',
10};
11
12// Using call() - arguments are passed individually
13person.introduce.call(employee, 'Manager', 'Sales');
14// Returns: "Hello, I'm Sarah, Manager in Sales"
15
16// Using apply() - arguments are passed as an array
17person.introduce.apply(employee, ['Manager', 'Sales']);
18// Returns: "Hello, I'm Sarah, Manager in Sales"

Both methods achieve the same outcome, with the choice between them typically depending on whether your arguments are available as separate values or as an array.

Finished reading?

Mark this topic as solved to track your progress.