Call, Apply and Bind in JavaScript

call, apply, and bind are three built-in functions in JavaScript that allow you to change the context in which a function is executed. These functions are commonly used in functional programming.

Here's a brief overview of what each of these functions does:

Call

This function is used to call a function with a specified this value and arguments provided individually. It allows you to pass a specific object as the this value for the function to be executed on. For example:

function greeting(name) {
  console.log(`Hello, ${name}! My name is ${this.name}.`);
}

const person = { name: 'John' };

greeting.call(person, 'Sarah'); // output: Hello, Sarah! My name is John.

In the above example, call is used to call the greeting function with person object as the this value, and Sarah as the name argument.

Apply

This function is similar to call, but it allows you to pass arguments as an array instead of individually. For example:

function greeting(name) {
  console.log(`Hello, ${name}! My name is ${this.name}.`);
}

const person = { name: 'John' };
const args = ['Sarah'];

greeting.apply(person, args); // output: Hello, Sarah! My name is John.

In the above example, apply is used to call the greeting function with person object as the this value, and ['Sarah'] as the args array.

Bind

This function is used to create a new function with a specified this value and arguments, without invoking the original function. It allows you to bind the this value permanently to a specific object, which can be useful in some cases. For example:

function greeting(name) {
  console.log(`Hello, ${name}! My name is ${this.name}.`);
}

const person = { name: 'John' };

const boundGreeting = greeting.bind(person);
boundGreeting('Sarah'); // output: Hello, Sarah! My name is John.

In the above example, bind is used to create a new function boundGreeting that permanently binds the this value to the person object, and then the new function is called with the name argument 'Sarah'.

In summary, call, apply, and bind are three useful functions in JavaScript that allow you to change the context in which a function is executed, and can be particularly useful in functional programming.

Interactive example

CodeSandBox