Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Introducing ES2015 The Cooler Parts of ES2015 Rest Parameters and Spread Operator

REST params must be last parameter listed?

If someone can clarify that would be great. Thanks!

3 Answers

Manish Giri
Manish Giri
16,266 Points

It means that if your function has regular methods parameters, and a rest parameter, then the rest parameter should be the last one declared, like so -

function foo(a, b, ...c) {
 // c is a rest parameter
}

Thank you @Manish Giri for confirming what I had suspected. Simple answer and straight to the point!

The 'rest' in the ES2015 'rest parameter' is different than the 'rest' as in REST API (Representational State Transfer). Guil is referring to the new syntax that allows you to represent an indefinite number of function arguments as an array. The only stipulation is that this new parameter (which can be treated as an array inside the function) must be the last one listed in the function declaration. Think of it as meaning "just the rest of the parameters that have yet to be explicitly defined." So,

// Throws `SyntaxError: Rest parameter must be last formal parameter`
function f(a, ...theArgs, b) {
  return theArgs.length;
}

// Correct
function f(a, b, ...theArgs) {
  return theArgs.length;
}

Check out this MDN article on rest parameters for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters.

Erika Suzuki
Erika Suzuki
20,299 Points

Yes, same as Python's concept. It should be last or second to last if **kwargs (keyword arguments) are present.

def func_name(*args, **kwargs):
    pass