[JavaScript] Using Rest Parameters for Flexible Functions with Any Number of Arguments

目次

Overview

When defining a function, there are cases where you do not know exactly how many values the caller will provide. By using the “Rest Parameters” syntax introduced in ES6, you can gather an arbitrary number of arguments into a single array. This article demonstrates how to use this syntax to implement a process that sums up multiple numerical values.

Specifications (Input/Output)

  • Input: An arbitrary number of numerical values (e.g., 10, 20, 30…).
  • Output:
    • The total sum of the provided numbers.
    • A count of how many arguments were passed (array length).

Basic Usage

In the function’s argument definition, write ... (three dots) before the parameter name. This automatically stores the passed values into an “array” that can be used inside the function.

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rest Parameters Demo</title>
    <script src="rest-param.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>The calculation results using variable arguments are displayed in the console.</p>
    </div>
</body>
</html>

JavaScript (rest-param.js)

This implementation uses a scenario of totaling test scores. Since the received scores parameter is handled as an array, you can easily calculate the sum using a for...of loop.

/**
 * Function to calculate the sum of passed scores
 * @param {...number} scores - An arbitrary number of scores (received as an array)
 * @returns {number} Total score
 */
function calculateTotalScore(...scores) {
    console.log(`Number of items received: ${scores.length}`);
    console.log(`Contents:`, scores);

    let total = 0;
    
    // Iterate through the scores array and add each value
    for (const score of scores) {
        total += score;
    }

    return total;
}

// Pattern 1: Passing 3 arguments
const groupAScore = calculateTotalScore(80, 75, 90);
console.log(`Group A Total: ${groupAScore} points`); 
// Output: 245 points


// Pattern 2: Passing 5 arguments
const groupBScore = calculateTotalScore(100, 60, 70, 85, 95);
console.log(`Group B Total: ${groupBScore} points`); 
// Output: 410 points


// Pattern 3: Zero arguments
// The array becomes empty [], the loop does not run, and 0 is returned
const emptyScore = calculateTotalScore();
console.log(`No data Total: ${emptyScore} points`);
// Output: 0 points

Customization Points

  • Combining with Fixed Arguments: It is common in professional development to use a fixed variable for the first argument and collect the remaining ones in an array, such as function registerTeam(teamName, ...members).
  • Changing Logic: This approach can also be used for functions that find the maximum value using Math.max(...scores) or functions that calculate an average.

Important Points

  • Placement Restriction: Rest parameters (...parameterName) must always be at the end of the argument list. Writing it in the middle, such as function func(...args, lastParam), will cause a syntax error.
  • One Per Function: You can only use one rest parameter per function definition.

Advanced Usage

Shorter Syntax with the reduce Method

For totaling processes, using the reduce array method is more modern and concise than a for...of loop.

// Syntax using an arrow function and reduce
const sumAll = (...nums) => nums.reduce((acc, curr) => acc + curr, 0);

console.log(sumAll(10, 20, 30)); // 60

Summary

The ...parameterName syntax allows you to create flexible functions where the number of arguments is not determined in advance. Because the values are treated as a standard “array” inside the function, you can directly apply loops and array methods, which is a significant advantage for maintaining clean code.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次