Keno
Keno

Reputation: 3945

Use default parameter when using the spread syntax in ES6?

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

Upvotes: 3

Views: 1508

Answers (2)

Bergi
Bergi

Reputation: 664548

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);
  }
}

Upvotes: 2

joews
joews

Reputation: 30330

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

Upvotes: 2

Related Questions