Is it possible to set the default parameter value to the stop parameter

ES6 is a set of convenient syntactic sugar. Among them , the default option features JavaScript functions, as well as rest options . I found that my console (or devTools) complains (i.e. Throws an error) when trying to set the default parameter value for the rest parameter. I have found surprisingly few references to this particular problem elsewhere, and I wonder if 1.) can do this and 2.) why not (if this is not possible).

As an example, I came up with a trivial (but, hopefully, more focused) example. In this first iteration of the function, I built such a function to make it work (i.e., not giving the rest of the parameter a default value).

const describePerson = (name, ...traits) => `Hi, ${name}! You are ${traits.join(', ')}`; describePerson('John Doe', 'the prototypical placeholder person'); // => "Hi, John Doe! You are the prototypical placeholder person" 

However, now with the default value:

 const describePerson = (name, ...traits = ['a nondescript individual']) => `Hi, ${name}! You are ${traits.join(', ')}`; describePerson('John Doe'); // => Uncaught SyntaxError: Unexpected token = 

Any help is greatly appreciated.

+10
source share
2 answers

No, break parameters cannot have a default initializer. This is not allowed by the grammar, because the initializer will never be started - the parameter is always assigned an array value (but possibly empty).

What you want to do can be achieved with

 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(', ')}` 
+10
source

Just came to add a cleaner system by default:

 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 replaces the keys of the first object present in the second with the values ​​of the second.

If the second one does not have index 1, then it will not be overwritten, but if it has index 0, the index of the first array 0 will be overwritten by the second, which is the behavior that you expect in default.

Note that array expansion is not the same as object expansion, so [....['x', 'y'],...traits] will not overwrite indexes

0
source

Source: https://habr.com/ru/post/1265135/


All Articles