HomeJAVASCRIPTWhat is the difference between call, apply, and bind?

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

these three (call, apply, and bind) are JavaScript function methods that let you explicitly set the value of this when calling a function. The main difference is how arguments are passed and when the function is executed.


πŸ”Ή 1. call()

  • Executes the function immediately.
  • Arguments are passed individually (comma-separated).
function greet(greeting, punctuation) {
  console.log(greeting + " " + this.name + punctuation);
}

const person = { name: "Himanshu" };

greet.call(person, "Hello", "!");  
// Output: Hello Himanshu!

πŸ”Ή 2. apply()

  • Executes the function immediately.
  • Arguments are passed as an array (or array-like object).
greet.apply(person, ["Hi", "!!"]);  
// Output: Hi Himanshu!!

πŸ”Ή 3. bind()

  • Does NOT execute the function immediately.
  • Returns a new function with this bound and arguments pre-set (if any).
  • You call the returned function later.
const boundGreet = greet.bind(person, "Hey");
boundGreet("?");  
// Output: Hey Himanshu?

βœ… Key Differences

MethodExecutes Immediately?How Arguments Are PassedReturns
callβœ… YesIndividually (comma-separated)Result of the function
applyβœ… YesAs an arrayResult of the function
bind❌ NoIndividually (when binding)A new function with this bound

πŸ‘‰ Quick analogy:

  • call = “Call me now with these arguments.”
  • apply = “Apply this array of arguments and call me now.”
  • bind = “Bind me to this object and arguments, but don’t call yet β€” save me for later.”

Share:Β 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *