JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Function apply()

14 April 2025 | Category:

In JavaScript, the apply() method is used to call a function with a given this value and arguments provided as an array (or array-like object).

It works similarly to the call() method, but with one key difference: how the arguments are passed.


✅ Syntax

functionName.apply(thisArg, [arg1, arg2, ...])

Parameters:

  • thisArg: The value of this inside the function.
  • [arg1, arg2, ...]: An array of arguments.

🔍 Example: Using apply() to Set this

function introduce(language) {
  console.log(`I'm ${this.name}, and I speak ${language}.`);
}

const person = { name: "Amit" };

introduce.apply(person, ["Hindi"]); 
// Output: I'm Amit, and I speak Hindi.

💡 introduce is not a method of person, but apply() sets this to person.


🔁 Difference: call() vs apply()

Featurecall()apply()
ArgumentsPassed individuallyPassed as an array
Examplefunc.call(thisArg, a, b)func.apply(thisArg, [a, b])

🧠 Real-life Use Case: Math.max()

const numbers = [4, 7, 2, 9];

const max = Math.max.apply(null, numbers);
console.log(max); // Output: 9

You can’t pass an array directly to Math.max(), but apply() allows you to spread the array as arguments.


🧬 Function Borrowing with apply()

const person1 = { fullName: "Alice Cooper" };
const person2 = { fullName: "Bob Marley" };

function sayHello(greeting) {
  console.log(`${greeting}, I'm ${this.fullName}`);
}

sayHello.apply(person2, ["Hey"]); 
// Output: Hey, I'm Bob Marley

🔄 apply() + arguments Object

Sometimes used to forward arguments dynamically:

function sum() {
  return Array.prototype.reduce.apply(arguments, [(acc, curr) => acc + curr]);
}

console.log(sum(1, 2, 3, 4)); // 10

⚠️ Notes

  • In strict mode, if null or undefined is passed as thisArg, it stays as null or undefined.
  • In non-strict mode, null or undefined defaults to the global object (window in browsers).

🧾 Summary

  • apply() is great for calling functions with array-based arguments.
  • It gives you control over the this value and lets you dynamically pass arguments.
  • Perfect for scenarios like borrowing functions or spreading arrays as arguments.