HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Apply

The apply() method is very similar to the call() method. It allows an object to use a method belonging to another object, but with one major difference: apply() takes arguments as an array.


The Difference: call() vs apply()

While both methods explicitly set the value of this, they handle additional arguments differently:

  • call() takes arguments separately (comma-separated).
  • apply() takes arguments as an array.
const person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
const person1 = {
  firstName: "Mim",
  lastName: "Akter"
}

// apply() takes arguments in square brackets (array)
person.fullName.apply(person1, ["Oslo", "Norway"]);

Using apply() for Math Functions

The apply() method is particularly useful when you want to use built-in functions like Math.max() on an array of numbers. Normally, Math.max() only accepts individual numbers.

const numbers = [5, 6, 2, 3, 7];

// Math.max(5, 6, 2, 3, 7) would be hard with a dynamic array
let max = Math.max.apply(null, numbers); 
console.log(max); // 7
Tip: In the example above, we passed null as the first argument because Math.max does not depend on any specific object for its this value.

Key Points to Remember

  • apply() invokes a function with a given this value
  • Arguments must be passed as an Array []
  • It is more convenient than call() when your data is already in an array
  • Commonly used with Math methods to process array data
  • In strict mode, if the first argument is not an object, it becomes the owner (not the global object)
  • With modern JavaScript, the Spread operator (...) is often used instead of `apply()`.