One, the extension of the function chapter

1.1 Default Values of function parameters

When we use js to declare a function, sometimes we need to declare the default value of the function, we generally operate like this:

function log(x,y){
    y = y || "Default value";console.log(x,y); } call the function: log("hello") // Hello is the default value
log("hello"."China") // hello China
log("hello"."") // Hello is the default value

Copy the code

The above code checks to see if the parameter y to the function log is assigned a value, and if not, specifies a default value of World. The disadvantage of this notation is that if y is assigned, but the corresponding Boolean is false, the assignment does not work. As in the last line of the code above, the argument y equals the null character, and the result is changed to the default value.

To avoid this problem, it is often necessary to check whether y is assigned and, if not, equal to the default.

if (typeof y === 'undefined') {
  y = 'World';
}
Copy the code

Using ES6 syntax we could write:

function log(x,y="World"){
	console.log(x,y)
}
log("hello") //hello World
log("hello"."China") //Hello China
log("hello"."") // hello
Copy the code

ES6 functions declare default value constructor examples

  function Point(x = 0, y = 1) {
      this.x = x;
      this.y = y;
  }
const p = new Point(3.4);
console.log(p)
Copy the code

1.2 ES6 benefits of declaring defaults:

In addition to brevity, ES6 writing has two benefits: first, readers of the code can immediately recognize which parameters can be omitted without having to look at the function body or documentation; Secondly, it is beneficial for future code optimization. Even if the future version removes this parameter completely in the external interface, it will not cause the previous code to fail to run.

1.3 Parameter variables are declared by default, so they cannot be usedletorconstAgain.

We cannot use let or const to declare the default values again in the function body, otherwise we will get an error.

Uncaught SyntaxError: Identifier 'x' has already been declared
Copy the code

This means that x is already declared, but we can use var to declare it, which overrides the default

example

 function foo (x= 1) {
     let x = 1; // error
     const x = 2; // error  

     console.log(x)
     var x = 3
     console.log(x)
 } 
Copy the code

1.4 When default parameter values are used, functions cannot have parameters with the same name.

/ / is not an error
function foo(x, x, y) {
  // ...
}

/ / an error
function foo(x, x, y = 1) {
  // ...
}
Copy the code

Same argument x repeats

Another case:

let x = 99;
function foo(p = x + 1) {
  console.log(p);
}

foo() / / 100

x = 100;
foo() / / 101
Copy the code

In the code above, the default value of parameter p is x + 1. Instead of default p equals 100, each time the function foo is called, x + 1 is recalculated.

Note: It is easy to overlook that the default value of a parameter is not passed, but is recalculated each time. That is, the parameter defaults are lazily evaluated.

1.5 Default Values Are used in conjunction with the default values for deconstruction assignment

case

function foo({x, y = 5}) {
  console.log(x, y);
}

foo({}) // undefined 5 // x undefined default value
foo({x: 1}) // 1 5 //5 uses the default yes, 1 is the default value of the passed argument structure
foo({x: 1.y: 2}) / / 1. 2
foo() // TypeError: Cannot read property 'x' of undefined Foo () is an empty object as specified in the code above. If no argument is provided, the argument to function foo defaults to an empty object.Copy the code

The above code only uses the default values of the destruct assignment of the object, not the default values of the function arguments. The variables x and y are generated by destructuring assignments only if the argument to function foo is an object. If the function foo is called with no arguments, the variables x and y are not generated, resulting in an error. This can be avoided by providing default values for function arguments.

function foo({x, y = 5} = {}) {
  console.log(x, y);
}

foo() // undefined 5
Copy the code

Explanation: The above code specifies that if no argument is provided, the argument to function foo defaults to an empty object. One of the above situations occurs if you do not specify an empty object.

1.6 Deconstruct assignments and function defaults

function fetch(url , {body = "", method = "Get" , header = {} } = {} ) {
    console.log(url);
    console.log(method);
    console.log(body);
    console.log(header);
}
fetch( "http://www.baidu.com", { body : "I am a body".method: "POST" , header: 'Request header'  })
Copy the code

In this case, double defaults are used for function arguments

{body = “”, method = “Get”, header = {}} = {} First we’ll set the default values for body, method, and header. Again, set the default value for this object. The default value is an empty object, otherwise an error will be reported.

Error cases:

function fetch(url, { body = ' ', method = 'GET', headers = {} }) {
  console.log(method);
}
fetch('http://example.com', {})
// "GET"

fetch('http://example.com')
/ / an error
Copy the code

1.7 Case Differences

/ / write one
function m1({x = 0, y = 0} = {}) {
  return [x, y];
}

/ / write two
function m2({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}
Copy the code

Both methods set default values for function parameters. The difference is that the default values of function parameters are empty objects, but the default values of object deconstruction assignment are set. The default value of the two function arguments is an object with specific properties, but the default value of the object’s destruct assignment is not set.

// The function has no arguments
m1() / / [0, 0]
m2() / / [0, 0]

// both x and y have values
m1({x: 3.y: 8}) / / [3, 8]
m2({x: 3.y: 8}) / / [3, 8]

// if x has a value and y has no value
m1({x: 3}) / / [3, 0]
m2({x: 3}) // [3, undefined]

// if x and y have no values
m1({}) / / (0, 0),
m2({}) // [undefined, undefined]

m1({z: 3}) / / [0, 0]
m2({z: 3}) // [undefined, undefined]
Copy the code

1.8 About the Position of default Parameter Values

In general, the parameter that defines the default value should be the last parameter of the function. Because it’s easier to see what parameters are being omitted. If non-trailing arguments are set to default values, they cannot be omitted.

/ / a
function f(x = 1, y) {
  return [x, y];
}

f() // [1, undefined]
f(2) // [2, undefined])
f(, 1) / / an error
f(undefined.1) / / [1, 1)

/ / two cases
function f(x, y = 5, z) {
  return [x, y, z];
}

f() // [undefined, 5, undefined]
f(1) // [1, 5, undefined]
f(1.2) / / an error
f(1.undefined.2) / / [1, 5, 2)
Copy the code

None of the arguments with default values in the code above are tail arguments. In this case, you cannot omit this parameter without the argument that follows it, unless you explicitly enter undefined.

If undefined is passed, the parameter is triggered to equal the default value; null has no effect.

function foo(x = 5, y = 6) {
  console.log(x, y);
}

foo(undefined.null)
// 5 null
Copy the code

In the above code, the x parameter corresponds to undefined, which triggers the default value, and the y parameter equals null, which does not trigger the default value.

1.9 The length property of the function

// Demonstrate the length of the function's length property with a default value
var fnn =  function (a,b,c = 3) {
    console.log(  arguments.length );
}.length
console.log(fnn);  / / 2
Copy the code

The return value of the length attribute, 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 arguments, one of which c specifies the default value, so the length property is equal to 3 minus 1, resulting in 2.

function fn(a,b,c) {
    console.log(  arguments[]);// 3 function inside
    // arguments is a pseudo-array
    Arguments. length can be used to obtain the length of the array
}
fn(3.4.5)  // call the function fn
Copy the code

This is because the length attribute means that the function expects the number of arguments to be passed. When a parameter specifies a default value, it is not included in the expected number of parameters passed. Similarly, the rest parameters below do not count toward the Length attribute.

(function(. args) {}).length / / 0
Copy the code

If the parameter to which the default value is set is not the last parameter, the length attribute does not count toward subsequent parameters.

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

A digression —- the use of array expanders

var arr = [1.2.3.4.5 ]
var arr1 = ['a'.'a'.'d'.'f'.'g']
var arr3 = [...arr,...arr1]
console.log(arr3);
Copy the code

This operation can combine two numbers into an array, that is, array merge

2. Application of parameter default values

Using parameter defaults, you can specify that a particular parameter must not be omitted, and if omitted, an error is thrown.

1. Rest parameters

ES6 introduces the REST parameter (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object. The rest argument goes with a variable that puts the extra arguments into an array.

The rest argument is equivalent to arguments, putting the extra argument values in an array called VALUES, which is a real array.

function add(. values) {
  let sum = 0;

  for (var val of values) {
    sum += val;
  }

  return sum;
}

add(2.5.3) / / 10
Copy the code

The add function in the above code is a summation function that can be passed any number of arguments using the REST argument. Rest can put these parameters in an array.

Example:

function push(array, ... items) {
  items.forEach(function(item) {
    array.push(item);
    console.log(item);
  });
}

var a = [];
push(a, 1.2.3)
Copy the code

This example is an example of overwriting the array push method with the rest argument.

Note: The REST parameter cannot be followed by any other parameter (that is, only the last parameter), otherwise an error will be reported.

/ / an error
function f(a, ... b, c) {
  / /... The presence of the c argument causes this function to fail
}
/ / an error
function(...a,...b){
    	...b  // There is an error
}

Copy the code

The length property of the function, excluding the REST argument.

(function(a) {}).length  / / 1
(function(. a) {}).length  / / 0
(function(a, ... b) {}).length  / / 1
Copy the code

Unfinished…