Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

This can be done by two methods:

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. 

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

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. 

Syntax:

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

Example: In this example, we will see the use of spread syntax

Javascript




function passToFunction() {
    arrayToPass = [1, "Two", 3];
 
    unmodifiableFunction(...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


Last Updated : 07 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads