Is It Possible To Set Default Parameter Value On A Rest Parameter

Just came to add a cleaner defaults system:

const describePerson = (name, ...traits) => {
  traits = Object.assign(['x', 'y'], traits);

  return `Hi, ${name}, you are ${traits.join(', ')}`;
}

describePerson('z'); // you are z, y
describePerson('a', 'b', 'c'); // you are a, b, c
describePerson(); // you are x, y

This works because arrays are objects whose indices are keys, and Object.assign overrides the keys of the first object present in the second one with the values of the second one.

If the second one has no index 1, then it won't be overwritten, but if it has index 0, the first array's index 0 will be overwritten by the second, which is the behaviour you expect when defaulting

Note that spreading arrays is not the same operation as spreading objects, which is why [....['x', 'y'], ...traits] wouldn't overwrite the indices


No, rest parameters cannot have a default initialiser. It is not allowed by the grammar because the initialiser would never be run - the parameter always gets assigned an array value (but possibly an empty one).

What you want to do could be achieved by either

function describePerson(name, ...traits) {
     if (traits.length == 0) traits[0] = 'a nondescript individual';
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}

or

function describePerson(name, firstTrait = 'a nondescript individual', ...traits) {
     traits.unshift(firstTrait);
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}

// the same thing with spread syntax:
const describePerson = (name, firstTrait = 'a nondescript individual', ...otherTraits) =>
    `Hi, ${name}! You are ${[firstTrait, ...otherTraits].join(', ')}`