What is the difference between .call and .apply in JavaScript?

Answer

The difference between .call() and .apply() in JavaScript lies in how they pass arguments to the function they invoke.

1. Function.prototype.call()

Syntax:

func.call(thisArg, arg1, arg2, ...);

Example:

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

const person = { name: 'Alice' };
greet.call(person, 'Hello', '!'); // Output: Hello, Alice!

2. Function.prototype.apply()

Syntax:

func.apply(thisArg, [arg1, arg2, ...]);

Example:

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

const person = { name: 'Bob' };
greet.apply(person, ['Hi', '?']); // Output: Hi, Bob?

When to Use?

MDN Web Docs: Function.prototype.call()

MDN Web Docs: Function.prototype.apply()