Skip to main content

difference between call bind apply

In JavaScript, callapply, and bind are methods used to control the this context within a function and to pass arguments to that function.
1. call()
  • Execution: Invokes the function immediately.
  • Arguments: Takes the this value as the first argument, followed by arguments for the function passed individually (comma-separated).
JavaScript
const person = {
  name: "Alice"
};

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

greet.call(person, "Hello", "!"); // Output: Hello, Alice!
2. apply()
  • Execution: Invokes the function immediately.
Arguments: Takes the this value as the first argument, followed by an array (or array-like object) of arguments for the function.
JavaScript
const person = {
  name: "Bob"
};

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

greet.apply(person, ["Hi", "."]); // Output: Hi, Bob.
3. bind()
Execution: 
Does not invoke the function immediately. Instead, it returns a new function with the specified this context permanently bound.
Arguments: 
Takes the this value as the first argument, optionally followed by arguments to be pre-filled (curried) into the new function. These pre-filled arguments will be used when the new function is eventually called.
JavaScript
const person = {
  name: "Charlie"
};

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

const boundGreet = greet.bind(person, "Hey");
boundGreet("?"); // Output: Hey, Charlie?
Summary of Differences:
Execution: 
call and apply execute the function immediately; bind returns a new function to be executed later.
Argument Handling: 
call takes arguments individually; apply takes an array of arguments; bind can take initial arguments that are pre-filled into the new function.
Return Value: 
call and apply return the result of the function execution; bind returns a new function.