1. The position of the default function parameter

Normally, the argument that defines the default value should be the trailing argument of the function. Because it’s easier to see what parameters are being omitted. If non-tail parameters are set to default values, actually

You can’t omit this parameter.

Function f(x = 1, y) {return [x, y]; } f () / / [1, undefined] f (2) / / / 2, undefined) f (1) / / an error f (undefined, 1) / / [1, 1] / / the function f (x, y = 5, z) { return [x, y, z]; } f () / / / undefined ", undefined, 5 f (1) / / [1, 5, undefined] f (1, 2) / / an error f (1, undefined, 2) / / [1, 5, 2)Copy the code

In the above code, none of the parameters with default values are tail arguments. At this point, you cannot omit this argument without omitting the arguments that follow it, unless undefined is explicitly entered.

If undefined is passed, the parameter is triggered to be equal to the default value; null does not.

function foo(x = 5, y = 6) {

console.log(x, y);

}

foo(undefined, null)

// 5 null
Copy the code

In the above code, undefined for the x argument triggers the default value, and null for the y argument does not trigger the default value.

2. The length attribute of the function

When the default value is specified, the length property of the function returns the number of arguments without a default value. That is, the length property is distorted when the default value is specified.

(function (a) {}).length // 1(function (a) {}).length // 1

(function (a = 5) {}).length // 0

(function (a, b, c = 5) {}).length // 2
Copy the code

In the above code, the return value of the length property is equal to the number of arguments to the function minus the number of arguments with default values specified. For example, the last function above defines three parameters, including one parameter

The number C specifies the default value, so the length property is equal to 3 minus 1, which is 2.

This is because the length property means the number of arguments that the function is expected to pass. When a parameter is specified with a default value, it is not included in the number of parameters expected to be passed. Similarly, rest parameters

The length attribute is not counted.

(function(... Args) {}).length // 0 If the default parameter is not a trailing parameter, the length attribute is no longer included in the following arguments. (function (a = 0, b, c) {}).length // 0 (function (a, b = 1, c) {}).length // 1Copy the code