1. Default values of function parameters


1.1 usage

In ES6, functions are allowed to set default values for parameters, mainly to improve the readability of the code, which is conducive to code optimization. Note also that when assigning a parameter, it cannot be used repeatedly and cannot be defined using let const.

/ / function by ES6 log (x, y) {y = y | | 'World'; if (typeof y === 'undefined') { y = 'World'; } console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', Function log(x, y = 'World') {console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello function Point(x = 0, y = 0) { this.x = x; this.y = y; } const p = new Point(); p // { x: 0, y: 0 } function foo(x = 5,x) { let x = 1; Const x = 2; const x = 2; }Copy the code
1.2 Used with deconstruction assignment

If the function is called without providing an argument, the internal variable will not be generated and an error will be generated. This can be resolved by providing a default value for the function, as follows:

function foo({x, y = 5}) { console.log(x, y); } foo () / / an error foo (1} {x:) / / 1 5 foo ({x: 2, y: 3) / / 2, 3, foo ({}) / / undefined 5 function foo ({x, y = 5} = {}) { Console. log(x,y)} foo() // undefined 5.Copy the code

Here’s an example:

function post(url, {b = ', type = 'get', h = {}}, {the console. The log (type)} post (' W.B.C '{}) / / get the post (' W.B.C') / / an error / / change to the function post(url, {b = '',type='get',h={}} = {}){ console.log(type) } post('w.b.c',{}) // get post('w.b.c') // getCopy the code

Here’s the difference

Function m1({x = 0, y = 0} = {}) {return [x, y]; } / / writing function 2 m2 ({x, y} = {x: 0, y: 0}) {return (x, y); } both of them have default values and it's the same if you call them both or if you don't pass them. M1 ({x: 0,0] m2({x: 0,0)) // undefined ({x: 0,0) 3}) // [3, 0] m2({x: 3}) // [3, undefined] m1({z: 3}) // [0, 0] m2({z: 3}) // [undefined, undefined]Copy the code
1.3 Positions of default Parameters

If the default value is defined, it should be the last parameter of the function. And this parameter cannot be omitted unless undefined is entered

1.4 The length attribute of the function

When a default value is specified for a function argument, the length property of the function is subtracted from the number of arguments that specified the default value. Because this attribute says that parameters with default values will not be included in the expected number of parameters. As follows:

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

If the parameters in a function are set to default values, the function declares initialization with a separate scope for the parameters, and the scope disappears when the initialization is complete, only if the parameters are set to default values. As follows:

var x = 1; function f(x, y = x) { console.log(y); } f(2) // 2 // the default value is set so that when f is called, the scope is set. When x is assigned to y, the value is 2, so y is 2. If x is not passed, then x will refer to the global value, so y = 1Copy the code
1.6 applications

Using parameter defaults, you can specify that one of the parameters must not be omitted. If omitted, an error is reported as follows

function throwIfMissing() {
  throw new Error('Missing parameter');
}

function foo(mustBeProvided = throwIfMissing()) {
  return mustBeProvided;
}

foo()
// Error: Missing parameter
foo(2) // 2
Copy the code

2. The rest parameters

The REST parameter was added to ES6 (… The rest argument is an array that puts the extra arguments into the array.

function add(... values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10 // Note: The rest argument cannot be followed by any other argument, and the rest argument does not count in the length attribute of the function.Copy the code

3. Strict mode

In ES6, if a function argument uses default values, deconstructed assignments, or extended operators, it cannot be explicitly set to strict mode inside the function, otherwise an error will be reported. Because the function is executed with its arguments first, the function body is executed, but because only in the function body can we know whether the arguments are executed in strict mode, the arguments should be executed before the function. There are two ways to circumvent this: set the global strict mode, and wrap the function in an immediate function with no arguments.

4. The name attribute

Return the function name of the function as follows:

function foo(){}
foo.name // foo

var f = function(){}
// ES5
f.name // ''
// ES6
f.name // f

var f = function c(){}

f.name // c
Copy the code

5. Arrow function

ES6 allows functions to be defined using arrows (=>)

var f = v => v; Var f = function (v) {return v; }; var f = () => 5; Var f = function () {return 5}; var sum = (num1, num2) => num1 + num2; Var sum = function(num1, num2) {return num1 + num2; }; Var sum = (num1, num2) => {return num1 + num2; // An example of the rest argument combined with the arrow function. const numbers = (... nums) => nums; Numbers (1, 2,3,4,5) // Const headAndTail = (head,... tail) => [head, tail]; HeadAndTail (1, 2,3,4,5) // [2,3,4,5]Copy the code
Pay attention to the point
1. The this object inside the function is the object at which it is defined, not used. 2. Do not use it as a constructor, that is, do not use the new command, otherwise an error will be thrown. You can't use arguments objects. This object does not exist in the function body. If you do, use the REST argument instead. 4. Arrow functions cannot be used as Generator functions because yield cannot be used. 5. Since arrow functions don't have their own this, they can't use call(), apply(), or bind() to change the direction of this.Copy the code
Not applicable Scenario
1. Define object methods that include this inside the method. 2. Dynamically define this situations, such as clicking the point to this in the eventCopy the code
Nested arrow functions

Arrow functions can be nested inside arrow functions.

6. Tail-call optimization

What is a tail call

An important concept of functional programming in which the last step of a function is to call another function

function f(x){ return g(x); Function f(x){let y = g(x); return y; Function f(x){return g(x) + 1; } function f(x){g(x); }Copy the code
Tail-call optimization

Only the inner function call frames are kept. If all functions are tail calls, then it is perfectly possible to have only one call frame item per execution, which would save a lot of memory. This is what tail-call optimization is all about.

function f() { let m = 1; let n = 2; return g(m + n); } f(); Function f() {return g(3); } f(); // same as g(3);Copy the code

Note that the call frame of the inner function replaces the call frame of the outer function only if the inner variables of the outer function are no longer used. Otherwise, tail-call optimization cannot be performed.

Tail recursion

The function calls itself, called recursion. If the tail calls itself, it is called tail recursion.

Tail-call optimization in ES6 is only enabled in strict mode, not in normal mode.
Implementation of tail recursive optimization

In normal mode, you can use the method of reducing the call stack and looping out the recursion

Welcome to pay attention to the public account [Xiaoyao students]

ES6 Introduction series

ES6 Introduction to let and cont

ES6 introduction to variable deconstruction assignment

ES6 starter string extension

ES6 – An extension to get started with re

ES6 introduction to numerical extension

Git tutorial

Front-end Git basics tutorial