Sobes.tech
Middle

What is the difference between call, apply, and bind methods in JavaScript?

sobes.tech AI

Answer from AI

Method Purpose Argument Passing Return Value
call Calls a function with a specified this context and separate arguments. Passed as separate arguments after the this context. The result of the function execution.
apply Calls a function with a specified this context and arguments passed as an array. Passed as an array (or array-like object) after the this context. The result of the function execution.
bind Returns a new function that, when called, has the specified this context and, optionally, pre-set arguments. Passed as separate arguments after the this context when calling bind. A new function with bound context and arguments.
// Example of using call
const obj = { name: 'Alice' };
function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}
greet.call(obj, 'Hello', '!'); // Outputs: Hello, Alice!
// Example of using apply
const obj2 = { job: 'Developer' };
function describe(title, company) {
  console.log(`I am a ${title} at ${company}.`);
}
const args = ['Frontend', 'TechCorp'];
describe.apply(obj2, args); // Outputs: I am a Frontend at TechCorp.
// Example of using bind
const obj3 = { city: 'New York' };
function showLocation() {
  console.log(`My city is ${this.city}.`);
}
const boundShowLocation = showLocation.bind(obj3);
boundShowLocation(); // Outputs: My city is New York.

// Example of bind with a pre-set argument
const obj4 = { value: 10 };
function addValue(num) {
  console.log(this.value + num);
}
const boundAddFive = addValue.bind(obj4, 5);
boundAddFive(); // Outputs: 15