How to use the apply() method In Javascript

This method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed. The apply() method is used on the function that has to be passed as the arguments array. The first parameter is specified as ‘null’ and the second parameter is specified with the arguments array. This will call the function with the specified arguments array. 

Syntax: 

arrayToPass = [1, "Two", 3];
unmodifiableFunction.apply(null, arrayToPass);

Example: In this example, we will pass the array using the apply method.

Javascript
function passToFunction() {
    arrayToPass = [1, "Two", 3];

    unmodifiableFunction.apply(null, arrayToPass);
}

function unmodifiableFunction(a, b, c) {
    console.log(`First value is: ${a}
Second value is: ${b}
Third value is:  ${c}`)
}
passToFunction()

Output
First value is: 1
Second value is: Two
Third value is:  3

How to pass an array as a function parameter in JavaScript ?

In this article, we will learn how to pass an array as a function parameter in JavaScript.

This can be done by two methods:

Table of Content

  • Method 1: Using the apply() method
  • Method 2: Using the spread syntax:
  • Method 3: Using the call() Method

Similar Reads

Method 1: Using the apply() method

This method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed. The apply() method is used on the function that has to be passed as the arguments array. The first parameter is specified as ‘null’ and the second parameter is specified with the arguments array. This will call the function with the specified arguments array....

Method 2: Using the spread syntax:

The spread syntax is used in places where zero or more arguments are expected. It can be used with iterators that expand in a place where there may not be a fixed number of expected arguments (like function parameters). The required function is called as given the arguments array using the spread syntax so that it would fill in the arguments of the function from the array....

Method 3: Using the call() Method

The call() method calls a function with a given this value and arguments provided individually. This method allows you to explicitly specify the this context and the arguments separately. To pass an array as arguments, you can use the spread syntax to expand the array elements as individual arguments....

Contact Us