Junior — Middle
What is the main difference between calling functions via bind and apply methods in JavaScript?
sobes.tech AI
Answer from AI
The main difference between bind and apply in JavaScript is:
bindcreates a new function with a bound context (this) and optionally initial arguments. This new function can be called later.applyimmediately invokes the function with a specified context and arguments passed as an array.
Example:
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Ivan' };
const boundGreet = greet.bind(person, 'Hello');
boundGreet('!'); // Outputs: Hello, Ivan!
// Using apply to invoke immediately
greet.apply(person, ['Hello', '.']); // Outputs: Hello, Ivan.