The default parameter values can be assigned default values and deconstruction, in combination.
function foo({x, y = 5}) { console.log(x, y); } foo({}) // undefined 5 foo({x: 1}) // 1 5 foo({x: 1, y: 2}) // 1 2 foo() // TypeError: Cannot read property 'x' of undefined
The above code uses the default value assignment deconstruction object only, not using the default values of function parameters. Only when the function foo
parameter is an object, variable x
, and y
will generate an assignment by deconstruction. If the function foo
is not provided when the call parameters, variables x
, and y
will not be generated, and thus an error. The default value provided by the function parameters, you can avoid this situation.
function foo({x, y = 5} = {}) { console.log(x, y); } foo() // undefined 5