What is call() ,apply() and bind() ?

What is call() ,apply() and bind() ?

call(), apply(), and bind() are methods available on JavaScript functions that allow you to manipulate the this value and pass arguments when calling a function.

call() Method

The call() method invokes a function with a specified this value and individual arguments passed as separate arguments. It accepts an object as the first argument, which will be the value of this inside the function, and any additional arguments are passed individually.

Example without arguments

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

const person = { name: 'John' };

greet.call(person);
// Output: John!

In this example, we define a greet() function that expects a name parameter. We also define a person object with a name property. We then call the greet() function with the call() method, passing in the person object as the this value .

Example with arguments

function greet(name) {
  console.log(`Hello, ${name}! I am ${this.title}.`);
}

const person = { title: 'Mr' };

greet.call(person, 'John');
// Output: Hello, John! I am Mr.

apply() Method

apply() method works similar to the call() method. but there is one difference between them is the call() method we pass arguments using a comma-separated list whereas apply() method we pass an array of arguments.

Example

function greet(name,sport) {
  console.log(`Hello, ${name}! I am ${this.title} I like ${this.sport}.`);
}

const person = { 
title: 'Mr',
};

greet.apply(person,[ 'John',"Football" ]);
// Output: Hello, John! I am Mr I like Football

Bind() Method

The bind() method creates a new function with a specified this value and any initial arguments. Unlike call() and apply(), bind() doesn't immediately invoke the function but returns a new function with the bound this value and arguments. This allows you to call the function later or pass it around as a callback.

function greet(name) {
  console.log(`Hello, ${name}! I am ${this.title}.`);
}

const person = { title: 'Mr' };

const boundGreet = greet.bind(person);

boundGreet('John');
// Output: Hello, John! I am Mr.

Only difference between call() & bind() is:

bind() method gives you the copy of function which can be invoked later rather than directly invoking it just like in the call() method.