What is the difference between call, apply and bind?
All three exist to control the this binding of a function. The difference is in how they take the arguments and what they return.
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const user = { name: "Ada" };
// call: the arguments are listed one by one.
console.log(greet.call(user, "Hello", "!")); // "Hello, Ada!"
// apply: the arguments are listed as an array.
console.log(greet.apply(user, ["Hello", "?"])); // "Hello, Ada?"
// bind: returns a new function with the receiver already fixed.
const bound = greet.bind(user, "Hello");
console.log(bound("!")); // "Hello, Ada!"
console.log(bound.name); // "bound Hello"Call and apply both invoke the function immediately. The only difference between them is the shape of the argument list, and it does not matter for a modern engine. Apply is useful when you already have the arguments in an array, such as the result of a map over a list, and call is useful when you have a fixed set of arguments.
Bind does not call anything. It returns a new function whose this is permanently set to the receiver you gave it, with any leading arguments already applied. Calling that returned function later passes the receiver automatically, which is what makes it the right tool for callbacks and event listeners.
Two details worth knowing. The bound function has a name and a length that reflect the binding, which is why the name shows the word bound in front of it. And bind can be called more than once, each time adding another leading argument, which is how you build a partially applied function.