Difference between Call, Apply and Bind

Barış Gündüz
2 min readMay 4, 2023

--

Call is a function that helps you change the context of the invoking function. In layperson’s terms, it helps you replace the value of this inside a function with whatever value you want.

Apply is very similar to the call function. The only difference is that in apply you can pass an array as an argument list.

Bind is a function that helps you create another function that you can execute later with the new context of this that is provided.

Call: The call() method invokes a function with a given this value and arguments provided one by one

var employee1 = { firstName: "Baris", lastName: "Gunduz" };
var employee2 = { firstName: "John", lastName: "Doe" };

function invite(greeting1, greeting2) {
console.log(
greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
);
}

invite.call(employee1, "Hello", "How are you?"); // Hello Baris Gunduz, How are you?
invite.call(employee2, "Hello", "How are you?"); // Hello John Doe, How are you?

Apply: Invokes the function with a given this value and allows you to pass in arguments as an array

var employee1 = { firstName: "Baris", lastName: "Gunduz" };
var employee2 = { firstName: "John", lastName: "Doe" };

function invite(greeting1, greeting2) {
console.log(
greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
);
}

invite.apply(employee1, ["Hello", "How are you?"]); // Hello Baris Gunduz, How are you?
invite.apply(employee2, ["Hello", "How are you?"]); // Hello John Doe, How are you?

Bind: returns a new function, allowing you to pass any number of arguments

var employee1 = { firstName: "Baris", lastName: "Gunduz" };
var employee2 = { firstName: "John", lastName: "Doe" };

function invite(greeting1, greeting2) {
console.log(
greeting1 + " " + this.firstName + " " + this.lastName + ", " + greeting2
);
}

var inviteEmployee1 = invite.bind(employee1);
var inviteEmployee2 = invite.bind(employee2);
inviteEmployee1("Hello", "How are you?"); // Hello Baris Gunduz, How are you?
inviteEmployee2("Hello", "How are you?"); // Hello John Doe, How are you?

Call and apply are pretty interchangeable. Both execute the current function immediately. You need to decide whether it’s easier to send in an array or a comma separated list of arguments. You can remember by treating Call is for comma (separated list) and Apply is for Array.

Whereas Bind creates a new function that will have this set to the first parameter passed to bind().

Follow me on Twitter, Instagram and if you want also on Github :) I also upload videos to Youtube from time to time.

Reference:

1- https://github.com/sudheerj

2- https://www.freecodecamp.org/news/understand-call-apply-and-bind-in-javascript-with-examples/

--

--

Barış Gündüz
Barış Gündüz

Written by Barış Gündüz

💻 Software Engineer 🏦 Owner @gunduzmedya 🎬 Content Creator

No responses yet