Javascript Function apply()

The apply() method calls a function with the passed this keyword value and arguments provided in the form of an array.

Example


apply() Syntax

The syntax of the apply() method is:

func.apply(thisArg, argsArray)

Here, func is a function.


apply() Parameters

The apply() method can take two parameters:

  • thisArg - The value of this which is provided while calling func.
  • argsArray (optional) - An array containing the arguments to the function.

apply() Return Value

  • Returns the result of the called function with the specified this value and arguments.

Example 1: apply() Method to call a Function

Output

Taylor, Good morning. How are you?

In the above program, we have used the apply() method to invoke the greet() function.

Inside the apply() method, the parameter:

  • personName - is this value
  • ["Good morning", "How are you?"] - are values for "wish" and "message" parameters of the greet() function

The method calls the greet() function so the result variable holds the return value of greet().


Apart from calling a function, we can use the apply() method for:

  • Function borrowing
  • Append an array

Example 2: apply() for Function Borrowing

Output

The Duke is of black color.

In the above program, we have borrowed the method of car object in the bike object with the help of the apply() method.


Example 3: apply() to Append two Arrays

Output

[ 'Red', 'Green', 'Blue', 'Yellow', 'Black' ]

Example 4 : Using apply() with built-in functions

Output

8
8

Recommended Reading: JavaScript Function call()