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
1const person = {2 name: 'John',3 greet: function () {4 return `Hello, ${this.name}`;5 },6};78const manager = {9 name: 'Sarah',10};1112// Using the greet function with manager's context13person.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};78const employee = {9 name: 'Sarah',10};1112// Using call() - arguments are passed individually13person.introduce.call(employee, 'Manager', 'Sales');14// Returns: "Hello, I'm Sarah, Manager in Sales"1516// Using apply() - arguments are passed as an array17person.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.
Related JavaScript interview topics
Continue with nearby questions from the same topic cluster.
What is the difference between call( ) and bind( )?What is the difference between async and defer in JavaScript?What is the difference between == and === in JavaScript?What is the difference between currying and partial application?What is the difference between dot notation and bracket notation?What is difference between stopPropagation() and stopImmediatePropagation()?