Course contentsShow
← JavaScript
Lesson 413 of 2,72311. FunctionsFree lesson

Rest Parameters Must Be Last

Learn the syntax requirement that rest parameters must appear at the end of the parameter list.

Rest Parameters Must Be Last

You'll learn the strict syntax rule that rest parameters can only appear as the final parameter in a function's parameter list.

Why This Rule Exists

When you use the rest parameter syntax (...args) to collect remaining arguments into an array, JavaScript needs to know where to stop assigning individual parameters and start bundling leftovers. If the rest parameter appeared anywhere except the end, JavaScript couldn't determine which arguments belong to parameters that follow it.

Think of it like packing a suitcase: you can pack specific items first (shoes, shirts, pants), but once you say "throw everything else in this bag," there's nothing left to organize afterward. The "everything else" bag must be last.

The Rule in Practice

This is valid:

function greet(greeting, ...names) {
  return `${greeting}, ${names.join(' and ')}!`;
}

greet('Hello', 'Alice', 'Bob', 'Charlie');
// "Hello, Alice and Bob and Charlie!"

This is invalid and causes a syntax error:

// ❌ SyntaxError: Rest parameter must be last formal parameter
function broken(...extras, lastName) {
  // How would JavaScript know which values go to extras vs lastName?
}

You also cannot have multiple rest parameters:

// ❌ SyntaxError
function invalid(...first, ...second) {
  // JavaScript can't split arguments between two "collect everything" buckets
}

Valid Patterns

Rest parameters work fine alongside regular parameters and default parameters—just keep the rest parameter at the end:

function processData(required, optional = 'default', ...rest) {
  console.log(required, optional, rest);
}

Key Takeaway: Rest parameters must always be the last parameter in the function signature because JavaScript needs to collect all remaining arguments after assigning earlier parameters.