JavaScript Function apply()


Method Reuse

Using the apply() method allows you to create a function that can be employed with various objects.


The JavaScript apply() Method

The apply() method is like the call() method, which was discussed in the previous chapter.

Here, the fullName function of the person is used on person1.


The Difference Between call() and apply()

The difference is:

The call() method accepts arguments individually.

The apply() method accepts arguments in the form of an array.

The apply() method is useful when you prefer using an array instead of a list of arguments.


The apply() Method with Arguments

The apply() method takes arguments in the form of an array.

In contrast to the call() method:


Simulate a Max Method on Arrays

To discover the biggest number in a list of numbers, you can utilize the Math.max() method.

JavaScript arrays don't come with a max() function, so you can use the Math.max() method instead.

The initial argument, which is set as "null," doesn't affect the outcome. In this example, it is not utilized.

The following examples will produce identical outcomes:


JavaScript Strict Mode

In JavaScript strict mode, when you use the apply() method, the first argument must be an object. If it's not an object, it will be considered as the owner (object) of the function that is called. In "non-strict" mode, if the first argument is not an object, it becomes the global object.