Curriculum Series

What is the difference between call( ) and bind( )?

What is the difference between call( ) and bind( )?

What is the difference between call( ) and bind( )?

JavaScript

call( ) vs bind( )

Both call( ) and bind( ) are methods that allow you to manipulate the this context of a function. They enable you to control what the this keyword refers to inside the function being called.

Here's an example to demonstrate this:

JAVASCRIPT
1const person = {
2 name: 'John',
3 greet: function () {
4 return `Hello, ${this.name}`;
5 },
6};
7
8const manager = {
9 name: 'Sarah',
10};
11
12// Using call() - executes the function immediately with manager's context
13person.greet.call(manager); // Returns: "Hello, Sarah"
14
15// Using bind() - returns a new function with manager's context
16const boundGreet = person.greet.bind(manager);
17boundGreet(); // Returns: "Hello, Sarah"

The difference between call and bind

The main differences between call() and bind() are:

  • call( ) executes the function immediately, while bind( ) returns a new function that can be called later.
  • call( ) changes the context for that specific function call, while bind( ) permanently sets the context for the returned function.
  • Both can accept arguments, but they handle them differently.
JAVASCRIPT
1const person = {
2 name: 'John',
3 introduce: function (role, department) {
4 return `Hello, I'm ${this.name}, ${role} in ${department}`;
5 },
6};
7
8const employee = {
9 name: 'Sarah',
10};
11
12// Using call() - executes immediately with arguments
13person.introduce.call(employee, 'Manager', 'Sales');
14// Returns: "Hello, I'm Sarah, Manager in Sales"
15
16// Using bind() - creates a new function with bound context
17const employeeIntroduce = person.introduce.bind(employee);
18employeeIntroduce('Manager', 'Sales');
19// Returns: "Hello, I'm Sarah, Manager in Sales"
20
21// bind() can also pre-set arguments when creating the function
22const salesIntroduce = person.introduce.bind(
23 employee,
24 'Manager',
25 'Sales'
26);
27salesIntroduce(); // All arguments are pre-set
28// Returns: "Hello, I'm Sarah, Manager in Sales"

In practical terms, use call() when you want to execute a function once with a different context, and use bind() when you want to create a reusable function with a specific context.

Finished reading?

Mark this topic as solved to track your progress.