What Is The Difference Between Call, Apply, And Bind Methods In JavaScript?

In JavaScript, call, apply, and bind are methods that can be used to set the context (this keyword) of a function when it's called.

The main difference between these methods is how they pass arguments to the function.

The call method allows you to call a function with a specified this value and arguments provided as a comma-separated list. For example:j

function greet(name) {
    console.log(`Hello, ${name}! My name is ${this.name}.`);
}
const person = {
    name: 'Alice'
};
greet.call(person, 'Bob');

In this example, call is used to call the greet function with person as the this value and 'Bob' as the name argument. The output will be:

Hello, Bob! My name is Alice.

The apply method is similar to call, but it expects the function arguments to be provided as an array. For example:

function sum(a, b) {
    return a + b;
}
const numbers = [1, 2];
sum.apply(null, numbers);

In this example, apply is used to call the sum function with null as the this value and [1, 2] as the arguments. The output will be,

3

The bind method is used to create a new function with a specified this value and any arguments pre-filled. It returns a new function that can be called later. For example:

function multiply(a, b) {
    return a * b;
}
const double = multiply.bind(null, 2);
double(5);

In this example, bind is used to create a new function called double that will multiply its argument by 2. The null argument is used to specify that the this value should be null. The 5 argument is passed when double is called. The output will be,

10

In summary, call and apply are used to immediately call a function with a specified context and arguments, while bind is used to create a new function with a specified context and pre-filled arguments that can be called later.


Similar Articles