The Rest Parameter in Javascript
Madeline
Posted on May 19, 2020
This works nicely, but what if we need to find the average of three numbers, or four, or five? Because we're lazy, we don't want to write a new function for each set of numbers. Instead, we want to use one function to do all of these calculations.
But what if we don't want to enter our numbers into the function as an array? What if we want to enter each one in as a parameter? But we still want to be able to enter a different number of parameters, depending on if we are calculating the average of 2 numbers, 4 numbers, or even 100 numbers.
We don't have a way to do this with our current syntax.
This is where the rest parameter comes in.
Here is what the syntax looks like:
As our function parameter we use (...numbers) to tell Javascript to grab all of the arguments passed into the function and put them into an array called "numbers".
This allows us to call the function by entering our individual numbers into the function call as parameters - as many as we need - instead of entering them in as a single array. We call the function with the values "0, 100, 88, 64" instead of the array "[0, 100, 88, 64]". But once the function is called, these values get added to an array. Then we can go about our business adding them all together, and dividing their sum by the length of the array to find out the average.
This gives us the flexibility to use this function for a variety of different cases.
BONUS:
With the rest parameter, we can even add non-number values into our function call! Let's imagine we'd like to use this function to give us a different message, depending on what we are calculating the average of. Maybe we want to know the average amount of customers who visited a restaurant in the last week, or the average temperature over the last 14 days, or the average score a student is getting on her tests.
Posted on May 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.