es6

Chapter 9: Function Rest Parameters in JavaScript (ES6)

Function Rest Parameter in JavaScript (ES6)

The rest parameter (...args) is a new feature introduced in ES6 that allows a function to accept an indefinite number of arguments as an array. This is especially useful when you don’t know how many parameters will be passed to a function.

πŸ”§ Syntax


function sum(a, b, ...args) {
  // a and b are named parameters
  // args is an array of remaining arguments
}
  

The rest parameter must always be the last in the function definition.

πŸ§ͺ Example: Adding Multiple Numbers


function sum(...args) {
  let total = 0;
  for (let arg of args) {
    total += arg;
  }
  return total;
}

let result1 = sum(6, 9, 34, 25, 29, 66, 77);  // 246
let result2 = sum(6, 9);                     // 15

console.log(result1);
console.log(result2);
  

Explanation: All arguments passed to the sum() function are collected in the args array and then summed using a for...of loop.

🚫 Incorrect Usage of Rest Parameters

The rest parameter must be the last in the parameter list. The following examples will throw syntax errors:


// ❌ Rest in the middle
function sum(a, ...rest, b) {
  // SyntaxError
}

// ❌ Rest at the beginning
function sum(...rest, a, b) {
  // SyntaxError
}
  

Correct Usage: The rest parameter should always appear at the end of the argument list.

πŸ“˜ Real-World Use Case

Use rest parameters when writing utility functions where the number of inputs can vary:


function logMessages(...messages) {
  messages.forEach(msg => console.log("Log:", msg));
}

logMessages("Server started", "User logged in", "Data loaded");
  

In this example, the function can handle logging any number of messages passed to it.

πŸ“˜ Assignments: Practice Rest Parameters

  1. Create a function multiplyAll(...nums) that multiplies all the numbers passed to it.
  2. Write a function filterNumbers(...args) that returns only the numbers greater than 10.
  3. Try defining a function with rest parameters in the middle of the argument list. What error do you get?
  4. Write a function logUserData(id, name, ...roles) that logs user info and any number of assigned roles.
  5. Compare rest parameter to spread operator in terms of direction: one collects, one expands.

πŸ“Œ Summary

  • Rest parameter ...args collects all remaining arguments into an array.
  • Must be the last parameter in the function definition.
  • Useful for functions with unknown or variable number of inputs.
  • Improves code flexibility and reduces need for manual argument handling.

Leave a Reply

Your email address will not be published. Required fields are marked *