Dot Net For All

How to send an array as method parameter using JavaScript Rest Parameters

Hello friends, this article is continuation of the online JavaScript learning series for beginners. In this article I will show you how you can send an array as method parameter using JavaScript Rest Parameters in JavaScript.

You can practice about JavaScript using plnkr as I have mentioned in my article: Live JavaScript programming practice with plnkr

Send an array as parameter using JavaScript Rest Parameters

Rest parameters allows a method to have multiple parameters as an array. Lets see the example of what I am talking about.

function multipleParameterMethod(...methParameters)
{
 methParameters.forEach(id => console.log(id));
}

multipleParameterMethod(1,2,'test');

As you can see in the above code I am passing multiple parameters to my method multipleParameterMethod.Therefore all these parameters are stored as array in methParameters variable.

Consequently in the method I am iterating over the array using forEach. And the result would be

//1

//2

//test

Below is more code example of Rest parameter. In the below code I have used rest parameter with another parameter.

function multipleParameterMethod(firstPara, ...parameters)
{
 parameters.forEach(id => console.log(id));
}

multipleParameterMethod('Monday',1,2,'test');

Due to this Rest parameters got their name. They can be used after rest of the parameters.
One important point to remember is that the rest parameter should be the last parameter in the method. If not so you may get an error.

To learn more about JavaScript you can visit this URL for online resources: JavaScript online articles for Beginners

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview