Average with Rest Parameters
Write a JavaScript function that uses rest parameters (...) to accept any number of arguments and returns their average (mean). Rest parameters collect all remaining arguments into a single array, allowing the function to handle variable numbers of inputs without using the arguments object.
Rest parameters were introduced in ES6 and provide a cleaner syntax than the older arguments object. Unlike arguments, rest parameters are a real array, so all array methods like reduce, map, and forEach are available directly. The syntax (...nums) in the function signature collects all passed arguments into an array named nums.
To calculate the average, use Array.reduce() to sum all numbers in the rest array, then divide by the array length. The reduce method accumulates the total, and the length gives the count. This combination of rest parameters with array methods is a hallmark of modern JavaScript functional programming.
Time complexity is O(n) where n is the number of arguments. The reduce method visits each argument exactly once. Space complexity is O(n) for the rest parameter array. The function gracefully handles any number of arguments from 1 to many.
Edge cases include a single argument (return the argument itself), negative numbers (handle correctly in sum), zero values, and the empty case (return 0 if no arguments provided by checking the length of the rest array).
Example Input & Output
Average of -5 and 5 is 0
All zeros
Average of 1..5 is 3
Average of 10,20,30 is 20
Single argument average is itself
Algorithm Flow

Solution Approach
Best Answers
function solution(...nums) {
if (nums.length === 0) return 0;
var sum = nums.reduce(function(acc, curr) {
return acc + curr;
}, 0);
return sum / nums.length;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
