Sobes.tech
Junior

What does the apply function do in JavaScript?

sobes.tech AI

Answer from AI

Calls a function with a specified this value and arguments provided as an array (or array-like object).

Main uses:

  • Changing the execution context of the function (this).
  • Passing arguments as an array.

Comparison with call and bind:

Method Arguments this context Return
apply Array/array-like object Set Result of the function call
call Separate arguments (comma-separated) Set Result of the function call
bind Separate arguments (comma-separated) Set New function with bound context

Example usage:

// Function definition
function greet(greeting, name) {
  console.log(`${this.title} ${greeting}, ${name}!`);
}

const person = { title: 'Mr.' };
const args = ['Hello', 'Alice'];

// Call function with changed context and arguments from array
greet.apply(person, args); // Outputs: Mr. Hello, Alice!
What does the apply function do in JavaScript… - sobes.tech