Prior to ES6, you could not directly specify default values for function parameters, only workarounds could be used.
1 2 3 4 5 6 7
functionlog(x, y) { y = y || 'World'; console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello World
The disadvantage is that if the parameter y is false, the assignment has no effect. In order to avoid this problem, it is usually necessary to first determine whether the parameter y is assigned, and if not, it is equal to the default value.
1 2 3
if (typeof y === 'undefined') { y = 'World'; }
ES6 allows you to set default values for function parameters, that is, write directly after the parameter definition.
1 2 3 4 5 6 7
functionlog(x, y = 'World') { console.log(x, y); }
log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello
rest parameter
The variable in the rest parameter represents an array, so array-specific methods can be used for this variable. The following is an example of rewriting the array push method using the rest parameter.
Note that there can be no other parameters after the rest parameter (that is, only the last parameter), otherwise an error will be reported. The length property of the function, excluding the rest parameter.
The spread operator is three dots (…). It is like the inverse of the rest parameter, turning an array into a sequence of parameters separated by commas.