JavaScript Function Apply
JavaScript Basics

JavaScript Function Apply

Function apply

Using the JavaScript apply() Method for Method Reuse

The apply() method in JavaScript functions similarly to the call() method but differs in how it handles arguments. It allows you to invoke a method belonging to one object on another object, and is particularly useful for passing an array of arguments.

Basic Use of apply()

The apply() method enables you to invoke a function, setting the this context explicitly, and passing an array of arguments.

const person = {  fullName: function() {   
return `${this.firstName} ${this.lastName}`;  }};‍const person1 = 
{  firstName: "Mary",  lastName: "Doe"};‍
// Using apply() to call a method on another objectconsole.log(person.fullName.apply(person1));  // Outputs "Mary Doe"

Difference Between call() and apply()

  • call() accepts an argument list.
  • apply() accepts a single array of arguments.

This distinction is useful when your argument data is already in an array format.

apply() with Arguments

You can pass arguments to the function using an array with apply(), which is handy when you don't know the number of arguments in advance or they are dynamically determined.

Using apply() with Math.max()

The apply() method can be particularly useful when dealing with built-in functions like Math.max(), which does not natively accept an array as an input.

// Using Math.max on an array with apply()const numbers = [1, 2, 3];console.log(Math.max.apply(null, numbers));  // Outputs 3‍// Various values for the first argument in strict modeconsole.log(Math.max.apply(Math, numbers));  // Outputs 3console.log(Math.max.apply(" ", numbers));   // Outputs 3console.log(Math.max.apply(0, numbers));     // Outputs 3

The first argument in apply() sets the this context, which does not affect Math.max but is crucial in methods where this is used.

JavaScript Strict Mode and apply()

In strict mode, the first argument of apply() becomes the this value exactly as passed, even if it's not an object. In non-strict mode, non-object values as the first argument are treated as the global object.

Summary

The apply() method is a versatile tool in JavaScript for invoking functions with an array of arguments. It allows methods to be reused across different objects and contexts efficiently, especially when handling functions that require multiple or variable arguments.

Take a look into your desired course