Sobes.tech
Middle

What are the call, apply, and bind methods used for in JavaScript?

sobes.tech AI

Answer from AI

They are used to control the execution context (the value of this) of a function.

  • call: Invokes the function immediately with a specified this value and individual arguments.
  • apply: Invokes the function immediately with a specified this value and arguments provided as an array or array-like object.
  • bind: Creates a new function with a permanently bound this value and optionally preset arguments. The original function is not invoked immediately.

Main differences:

Method How arguments are passed Is the function invoked immediately? Return value
call Individually, separated by commas Yes Result of the function call
apply As an array or array-like object Yes Result of the function call
bind Individually, separated by commas No A new function with bound this

Usage examples:

const person = { name: 'Alice' };

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

// Using call
console.log(greet.call(person, 'Hello', '!')); // Output: Hello, Alice!

// Using apply
console.log(greet.apply(person, ['Hi', '.'])); // Output: Hi, Alice.

// Using bind
const boundGreet = greet.bind(person, 'Bonjour');
console.log(boundGreet('!')); // Output: Bonjour, Alice!

const anotherBoundGreet = greet.bind(person, 'Hola', '?');
console.log(anotherBoundGreet()); // Output: Hola, Alice?
What are the call, apply, and bind methods used for… - sobes.tech