Unlimited function parameters using Rest in JavaScript
Usually, when working with functions with JavaScript, the parameters that you pass into the function would be fixed in numbers.
Take the following for an example.
function updateUser(name, age) {
console.log(name, age);
}
updateUser('Cherika', 5);
Here, as you can tell, the updateUser
function accepts two parameters, and these parameters are fixed. You can not pass in additional parameters when calling this function.
But there may be a certain situation where you would need a variable number of parameters.
For instance, when accepting postal addresses from the user, the street, city, and state might be fixed. And so, we can write a function to collect this set of information like the following.
function saveAddress(street, city, state) {
console.log(street, city, state);
}
saveAddress('123 Street', 'NYC', 'New York');
But let’s say you want to collect more information regarding the address (like address 1, zip code, and country) without allocating a parameter for each of these fields. How would we do it?
Well, we can use rest parameters in this case.
Rest parameters
Rest parameters, as its name suggests, make use of the rest operator(...
) to collect “rest” of the parameters.
So, if we want to collect more information regarding the user’s address in the saveAddress
function, here’s how we can do it.
function saveAddress(street, city, state, ...restOfAddress) {
console.log(street, city, restOfAddress.join(' '))
}
As you can tell, a function definition’s last parameter can be prefixed with ...
, which will cause all remaining (user supplied) parameters to be placed within a standard JavaScript array.
In our case, restOfAddress
will hold all the additional details of the postal address as an array and can be processed just like a regular array. Like in the example, all the elements of the restOfAddress
array will be converted to a string using the join
function.
Here’s how we can call saveAddress
with additional details.
saveAddress(
'123 Street',
'NYC',
'New York',
'Address 1',
'123456',
'US'
);
// '123 Street' 'NYC' 'Address 1 123456 US'
Learn more about JavaScript visually using this sleek roadmap.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.