Conceptual Question

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

JavaScript

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
const person = {
name: 'John',
greet: function () {
return `Hello, ${this.name}`;
},
};
const manager = {
name: 'Sarah',
};
// Using the greet function with manager's context
person.greet.call(manager); // Returns: "Hello, Sarah"
person.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
const person = {
name: 'John',
introduce: function (role, department) {
return `Hello, I'm ${this.name}, ${role} in ${department}`;
},
};
const employee = {
name: 'Sarah',
};
// Using call() - arguments are passed individually
person.introduce.call(employee, 'Manager', 'Sales');
// Returns: "Hello, I'm Sarah, Manager in Sales"
// Using apply() - arguments are passed as an array
person.introduce.apply(employee, ['Manager', 'Sales']);
// 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.

Continue with nearby questions from the same topic cluster.