Function extension of ES6

Posted by kbascombe on Mon, 20 Dec 2021 20:45:15 +0100

1 default value of function parameter

After ES6, you can specify default values for function parameters:

As shown below, before ES6, we can specify default values for parameters in the following alternative ways:

function log(x, y) {
if (typeof y === 'undefined') {//Avoid using the specified default value when y is an empty string
	y = 'World';
}
 console.log(x, y);
}

log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello

It is much easier to write with default values:

function log(x, y = 'World') {
	console.log(x, y);
}

be careful:

  1. Parameter variables are declared by default, so they cannot be declared again inside the function with let or const;
  2. If the parameter uses a default value, the function cannot have a parameter with the same name. For example, function foo(x, x, y = 1) {...} An error will be reported, but if there is no default value, no error will be reported, for example, function foo(x, x, y) {...} No error will be reported;
  3. If the default value of the parameter is an expression, the value of the expression will be recalculated each time, that is, lazy evaluation.

1.1 location of parameter default values

If the parameter of the function defines the default value of the parameter, the parameter is the tail parameter by default (that is, the last parameter). If it is not the tail parameter, the parameter cannot be omitted, otherwise an error will be reported.

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

f(, 1) // Because the first parameter is omitted, an error will be reported at this time
f(undefined, 1) // [1, 1], if undefined is explicitly passed in here, no error will be reported.
f(unll, 1) // [null, 1]. If NULL is passed in, the default value will not take effect

1.2 scope of parameters

Once the default value of the parameter is set, when the function is declared and initialized, the parameter will form a separate scope (context), which will disappear after initialization.

Note: the above syntax behavior will not appear when the parameter default value is not set.

let x = 1;
function f(x, y = x) {
	console.log(y);
}
f(2) // 2. Here, the variable x is defined, so the value of y is the value of parameter x passed by the function

//If x is not defined, the of X will point to the outer global variable x
let x = 1;
function f(y = x) {
	let x = 2;
	console.log(y);
}
f() // 1

//If x is not defined, the of X will point to the global variable X of the outer layer, but x is not defined in the outer layer, and an error will be reported
function f(y = x) {
	let x = 2;
	console.log(y);
}
f() // ReferenceError: x is not defined

1.3 application scenarios of parameter default values

We can use the default value of the parameter to specify that a parameter cannot be omitted. If omitted, an error will be thrown:

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

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

foo() // Uncaught Error: Missing parameter

Of course, you can also set the parameter to be omitted, that is, the default value is undefined:

function foo(para1, optional = undefined) { 
	//...
}

2. Rest parameters

ES6 introduces the rest parameter. The syntax is Variable name, used to get redundant parameters of the function.

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

var a = [];
push(a, 1, 2, 3) // At this time, a is [1,2,3]

Note: rest is an array, while argument is not. It is an array like object, as shown in the following example: arguments needs to use array From converts it to an array before using array specific methods.

// How to write the arguments variable
function sortNumbers() {
	  return Array.from(arguments).sort();
}

// Writing method of rest parameter
const sortNumbers = (...numbers) => numbers.sort();

In addition, there can be no other parameters after the rest parameter. The following example will report an error:

function f(a, ...b, c) {
  // report errors
}

3 arrow function

ES6 allows the use of arrows to define functions. The syntax form of arrows is = >.

var f = () => 5;

//The arrow function above is equivalent to
var f = function () { 
	return 5 
};

The advantage of arrow function is its simplicity:

const isEven = n => n % 2 === 0;//Judge parity
const square = n => n * n;//Square

3.1 specific use of arrow function

If the arrow function has no parameters or contains multiple parameters, parentheses can be used to represent the parameter part, and the return value is on the right side of the arrow.

var sum = (num1, num2) => num1 + num2;

//If there is more than one statement in the code block of the arrow function, it can be enclosed in braces
var sum = (num1, num2) => { 
	//...
	return num1 + num2; 
}

If the arrow function has no return value, you need to add the void keyword, otherwise an error will be reported.

let fn = () => void doesNotReturn();

If it is returned as an object, the return keyword may not be added, but it needs to be enclosed in parentheses:

// report errors
let getTempItem = id => { id: id, name: "Temp" };

// If parentheses are added, no error will be reported
let getTempItem = id => ({ id: id, name: "Temp" });

Arrow functions can also be used in conjunction with variable deconstruction:

const full = ({ first, last }) => first + ' ' + last;
full({'first':'hello','last':'world'}); //"hello world"

const headAndTail = (head, ...tail) => [head, tail];
headAndTail(1, 2, 3, 4, 5)//[1,[2,3,4,5]]

3.2 precautions for using arrow function

  1. The arrow function does not have its own this object. Its internal this is the this of the outer code block. Because there is no this, the arrow function cannot be used as a constructor, that is, you cannot use the new command on the arrow function, otherwise an error will be thrown.

  2. The arrow function has no arguments object. If this object is used internally, it is the arguments object of the external function. We can use the rest parameter instead.

  3. The yield command cannot be used in an arrow function, so an arrow function cannot be used as a Generator function.

Topics: Javascript ECMAScript