Code Logo

Average with Rest Parameters

Published at25 Jul 2026
JavaScript Functions Medium 0 views
Like0

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

Example 1
Input
-5,5
Output
0
Explanation

Average of -5 and 5 is 0

Example 2
Input
0,0,0,0
Output
0
Explanation

All zeros

Example 3
Input
1,2,3,4,5
Output
3
Explanation

Average of 1..5 is 3

Example 4
Input
10,20,30
Output
20
Explanation

Average of 10,20,30 is 20

Example 5
Input
7
Output
7
Explanation

Single argument average is itself

Algorithm Flow

Recommendation Algorithm Flow for Average with Rest Parameters
Recommendation Algorithm Flow for Average with Rest Parameters

Solution Approach

function average(...nums) {
  if (nums.length === 0) return 0;
  var sum = nums.reduce(function(acc, curr) {
    return acc + curr;
  }, 0);
  return sum / nums.length;
}

Best Answers

javascript - Approach 1
function solution(...nums) {
  if (nums.length === 0) return 0;
  var sum = nums.reduce(function(acc, curr) {
    return acc + curr;
  }, 0);
  return sum / nums.length;
}