3

I understand that you can use the spread operator syntax with parameters (Rest Parameters) when defining a function in es6 , like so:

function logEach(...things) {
  things.forEach(function(thing) {
    console.log(thing);
  });
}

logEach("a", "b", "c");
// "a" // "b" // "c" 

My question :

Can you use the default parameter along with the spread syntax ? This doesn't seem to work:

function logDefault(...things = 'nothing to Log'){
  things.forEach(function(thing) {
    console.log(thing);
  });
}
//Error: Unexpected token = 
// Note: Using Babel
Keno
  • 3,694
  • 2
  • 21
  • 40
  • 2
    Why would that make any sense? `things` would be an array with the remaining arguments, with a default being empty array. – Alexander O'Mara Oct 18 '16 at 21:50
  • Couldn't you just check `things.length` to determine if nothing was passed? – Rob M. Oct 18 '16 at 21:59
  • 3
    `...things` is called a [rest parameter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/rest_parameters) (some people describe it as "gather"). The syntax is the same as spread, but it does the opposite. – joews Oct 18 '16 at 22:04
  • Related: [Spread Syntax vs Rest Parameter in ES2015 / ES6](https://stackoverflow.com/q/33898512). – Henke Mar 16 '21 at 12:09

2 Answers2

2

JavaScript doesn't support a default for rest arguments.

You could split the arguments and merge their values in the function body:

function logDefault(head = "nothing", ...tail) {
  [head, ...tail].forEach(function(thing) {
    console.log(thing);
  });
}

logDefault(); // "nothing"
logDefault("a", "b", "c"); // a, b, c
joews
  • 29,767
  • 10
  • 79
  • 91
2

No, a rest parameter gets assigned an empty array when there are no arguments left; there is no way to provide a default for it.

You'll want to use

function logEach(...things) {
  for (const thing of (things.length ? things : ['nothing to Log'])) {
    console.log(thing);
  }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375