Sobes.tech
Middle

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

sobes.tech AI

Answer from AI

call, apply, and bind are used to control the execution context (the value of this) of a function and to pass arguments.

  • call: Calls a function with a specified this value and arguments passed separately.
    const person = { name: 'Alice' };
    
    function greet(greeting, punctuation) {
      console.log(`${greeting}, ${this.name}${punctuation}`);
    }
    
    greet.call(person, 'Hello', '!'); // Output: Hello, Alice!
    
  • apply: Calls a function with a specified this value and arguments passed as an array (or array-like object).
    const person = { name: 'Bob' };
    
    function greet(greeting, punctuation) {
      console.log(`${greeting}, ${this.name}${punctuation}`);
    }
    
    greet.apply(person, ['Hi', '.']); // Output: Hi, Bob.
    
  • bind: Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. The function itself is not called immediately.
    const person = { name: 'Charlie' };
    
    function greet(greeting, punctuation) {
      console.log(`${greeting}, ${this.name}${punctuation}`);
    }
    
    const boundGreet = greet.bind(person, 'Yo');
    
    boundGreet('?'); // Output: Yo, Charlie?
    boundGreet('!'); // Output: Yo, Charlie!
    

Comparison table:

Method Arguments Passing Return Value Call Type
call Separately Result of the function execution Immediate call
apply Array Result of the function execution Immediate call
bind Separately New function with bound context Creates a function, not called immediately