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 contextperson.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 individuallyperson.introduce.call(employee, 'Manager', 'Sales');// Returns: "Hello, I'm Sarah, Manager in Sales"// Using apply() - arguments are passed as an arrayperson.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.
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()?