Sobes.tech
Junior — Middle

What is the difference between call and apply functions in the context of calling methods in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, the functions call and apply are used to invoke a function with an explicit context (this), but they differ in how they pass arguments:

  • call(thisArg, arg1, arg2, ...) — accepts a list of arguments separated by commas.
  • apply(thisArg, [argsArray]) — accepts arguments as an array or array-like object.

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'Anna' };

greet.call(person, 'Hello', '!');      // Hello, Anna!
greet.apply(person, ['Greetings', '...']); // Greetings, Anna...

apply is convenient when the arguments are already in an array, while call is used when the arguments are known and passed explicitly.

What is the difference between call and apply… - sobes.tech