Sobes.tech
Middle

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

sobes.tech AI

Answer from AI

bind creates a new function with the this context fixed. It does not invoke the original function immediately. call invokes the original function immediately, setting the this context and passing arguments individually.

Example:

const person = { name: 'Ivan' };

function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

// Using call - invokes the function immediately
console.log(greet.call(person, 'Hello', '!')); // Hello, Ivan!

// Using bind - creates a new function
const boundGreet = greet.bind(person, 'Hi');
console.log(boundGreet('?')); // Hi, Ivan?
console.log(boundGreet('!')); // Hi, Ivan!