1, problem,

When learning ES syntax, I was confused by the following two functions. It involves function parameter defaults, destruct assignment defaults, and destruct assignment

// code 1:
function move({x = 0, y = 0} = {}) {
    console.log([x, b]);
}
move({x: 3.y: 8}); / / [3, 8]
move({x: 3}); / / [3, 0]
move({}); / / [0, 0]
move(); / / [0, 0]

// code 2:
function move({x, y} = { x: 0, y: 0 }) {
    console.log([x, b]);
}
move({x: 3.y: 8}); / / [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); / / [0, 0]
Copy the code

2. Default value explanation

2.1 default values of function parameters

1. When no argument (including undefined) is passed in, the function takes the default value of the argument (alternate). 2. If there is an outgoing default value, the default value will be replaced.

// Pass the parameter directly
function move(x=0,y=0){console.log([x,y])}
move() / / [0, 0]
move(1) / / (1, 0]
move(1.1) / / [1, 1]
// Assign to pass
function move({x, y} = {x: 0, y: 0}) { console.log([x,y]); } move();// [0,0] move takes the default argument {x: 0, y: 0}
Copy the code

2.2. Deconstruct assignment defaults

1, es uses === = for comparison, so it must be strictly equal to undefined for the default value to take effect.

var {x, y = 5, z = 1} = {z = undefined};
x // undefined destruct failed
y // 5 The default value is undefined. The default value is used
z // 1 passes a value, which is exactly the same as undefined, using the default value
Copy the code

3. Refer to the explanation

Function move(different arguments){console.log([x,y])}

Parameter passed in call The results of explain
move(x.y) Move (1, 2) [1, 2] The original assignment
move(x=0.y=0) move() [0, 0] Function parameters default values:x=0,y=0

Deconstructing assignment:Don't need

The arguments:There is no
move({x,y}) move({x:1,y:2}) [1, 2] Function parameters default values:There is no

Default value for destruct assignment:There is no

The arguments:{x,y}={x:1,y:2}
move({x=0,y=0}) move({x:1,y:2})

move({x:1})

move({y:2})

move({})

move()
[1, 2]

(1, 0]

[0, 2]

[0, 0]

An error
Deconstruct the assignment

Destruct assignment has default values
move({x=0,y=0}={}) move() [0, 0] If no parameter is passed or undefined is passed, the default value is {}, which resolves the error
move({x=0,y=0}={x:1,y:1}) move() [1, 1] Function parameters default values:{x:1,y:1}

Default value for destruct assignment:{x=0,y=0}

4. Comprehensive cases

function move({x = 0, y = 0} = { x: 1, y: 1 }) {
    console.log([x,y])
}
{x, y}
// The default value of destruct assignment is x = 0, y = 0

move({x: 3.y: 8}; {x: 3, y: 8}
/ / [3, 8]
move({x: 3}); {x: 3}
/ / [3, 0]
move({}); // Destructively assigned arguments: {}
/ / [0, 0]
move(); {x: 1, y: 1}
/ / [1, 1)
move(undefined); {x: 1, y: 1}
/ / [1, 1)
Copy the code