Learnitweb

What is the difference between call, apply and bind in JavaScript?

In JavaScript, this refers to the object that is currently executing the function. Its value depends on how the function is called. However, there are situations where you might want to explicitly set the value of this. This is where call, apply, and bind come into play.

1. The call Method

The call method invokes a function with a specified this value and arguments provided individually.

Syntax

functionName.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!
  • thisArg specifies the value of this inside the function.
  • Arguments are passed individually (comma-separated).

2. The apply method

The apply method is similar to ‘call’, but it takes arguments as an array (or an array-like object).

Syntax

functionName.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.
  • thisArg specifies the value of this inside the function.
  • Arguments are passed as an array or array-like object.

3. The bind Method

The bind method creates a new function with a specified this value and optionally pre-filled arguments. Unlike call and apply, it does not invoke the function immediately.

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

const person = { name: "Charlie" };
const boundGreet = greet.bind(person, "Hey");
boundGreet("!"); // Output: Hey, Charlie!
  • Returns a new function with this set to thisArg.
  • Arguments can be pre-filled, and additional arguments can be passed during invocation.

4. Comparing call, apply, and bind

Featurecallapplybind
InvocationImmediateImmediateDelayed (returns a new function)
Argument FormatIndividual argumentsArray or array-like objectIndividual (pre-filled or passed later)
Return ValueReturn value of the invoked functionReturn value of the invoked functionA new bound function