I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.
Lesson Objective for today
Yesterday function arrow function related based on search. Today is mainly to learn the parameter improvement of function in ES6 based on search. It’s another good day for learning. Come on, small and !!!!
Here I found a good summary website ~~~~, some of the content in the last two days is from this website ECMAScript 6 introduction, strong Amway!!!!
Default values for function arguments
Historical Causes
Before ES6, you could not specify default values for function parameters directly. You could only use workarounds.
function log(x, y) {
y = y || 'World';
console.log(x, y);
}
log('Hello') // Hello World log('Hello'.'China') // Hello China log('Hello'.' ') // Hello World 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
ES6 improvement
ES6 allows you to set default values for function arguments, which are written directly after the parameter definition.
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello'.'China') // Hello China log('Hello'.' ') // Hello Copy the code
As you can see, ES6 is much cleaner and more natural than ES5. Here’s another example.
function Point(x = 0, y = 0) {
this.x = x;
this.y = y;
}
const p = new Point(); p // { x: 0, y: 0 } Copy the code
In addition to brevity, ES6 writing has two benefits:
- The reader of the code can immediately recognize which parameters can be omitted without having to look at the function body or documentation.
- It is beneficial for future code optimization, even if future versions remove this parameter completely in the external interface, it will not cause the previous code to run.
Use case
Used in conjunction with deconstruction assignment
Parameter defaults can be used in conjunction with the default values of deconstructed assignments.
function foo({x, y = 5}) {
console.log(x, y);
}
foo({}) // undefined 5 foo({x: 1}) / / 1 5 foo({x: 1.y: 2}) / / 1. 2 foo() // TypeError: Cannot read property 'x' of undefined 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
The above code specifies that if no argument is provided, the argument to function foo defaults to an empty object.
The advanced case
/ / 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 the parameters of the function
- The default value of the function argument is
An empty object
, but the object is setDeconstruction assignment
theThe default value
; - The default value of the writing-two function argument is an object with specific properties, but no set object
Deconstruction assignment
The default value of.
// 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
Using parameter defaults, you can specify that a particular parameter must not be omitted, and if omitted, an error is thrown.
function throwIfMissing() {
throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
return mustBeProvided; } foo() // Error: Missing parameter Copy the code
The foo function in the above code, if called with no arguments, will call the default throwIfMissing function, throwing an error.
You can also see from the code above that the default value of the parameter mustBeProvided is equal to the result of the throwIfMissing function (note the parentheses after the function name throwIfMissing), which indicates that the default value of the parameter is not executed at definition, but at runtime.
If the parameter is already assigned, the function in the default value will not run.
Setting the parameter default to undefined indicates that the parameter can be omitted.
function foo(optional = undefined) {...}Copy the code
Matters needing attention
The default value of the argument will only be compared with 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.
Parameter variables are declared by default, so they cannot be declared again with let or const.
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}
Copy the code
In the above code, the parameter variable x is declared by default. It cannot be declared again in the function body using let or const, otherwise an error will be reported.
When using parameter defaults, functions cannot have arguments of the same name
/ / is not an error
function foo(x, x, y) {
// ...
}
/ / an error function foo(x, x, y = 1) { // ... } // SyntaxError: Duplicate parameter name not allowed in this context Copy the code
Also, it is easy to overlook that the parameter defaults are not passed, but are recalculated each time the default expression is evaluated. That is, the parameter defaults are lazily evaluated.
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.
Parameter defaults are usually placed at the end of the default
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.
The length property of the function
When a default value is specified, the length property of the function returns the number of arguments for which no default value is specified. That is, the length attribute is distorted when a default value is specified.
(function (a) {}).length / / 1
(function (a = 5) {}).length / / 0
(function (a, b, c = 5) {}).length / / 2
Copy the code
In the code above, the return value of the length attribute is equal to the number of arguments to the function minus the number of arguments to which the default value is 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.
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.
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
Scope limitation
Once the default values of parameters are set, the parameters form a separate context when the function is declared initialized.
After initialization, the scope will disappear. This syntactic behavior does not occur if the parameter defaults are not set.
var x = 1;
function f(x, y = x) {
console.log(y);
}
f(2) / / 2 Copy the code
In the code above, the default value of parameter y is equal to variable x. When f is called, the arguments form a separate scope.
In this scope, the default variable x refers to the first parameter x, not the global variable x, so the output is 2.
Look at the following example.
let x = 1;
function f(y = x) {
let x = 2;
console.log(y);
} f() / / 1 Copy the code
In the above code, the function f is called with the argument y = x forming a separate scope. In this scope, the variable x itself is undefined, so it points to the outer global variable x. When a function is called, the local variable x inside the function body does not affect the default variable x.
If the global variable x does not exist at this point, an error is reported.
function f(y = x) {
let x = 2;
console.log(y);
}
f() // ReferenceError: x is not defined Copy the code
If I write it this way, I’ll get an error.
var x = 1;
function foo(x = x) {
// ...
}
foo() // ReferenceError: x is not defined Copy the code
In the code above, the parameter x = x forms a separate scope. Instead, let x = x is executed, and due to a temporary dead zone, this line of code will report an error that x is undefined.
If the default value of an argument is a function, the scope of that function also follows this rule. Take a look at the following example.
let foo = 'outer';
function bar(func = () = >foo) {
let foo = 'inner';
console.log(func());
} bar(); // outer Copy the code
In the above code, the default value of func to the function bar is an anonymous function that returns the variable foo. Foo is not defined in the separate scope of the function argument, so foo refers to the outer global variable foo, so it prints outer.
If written as follows, an error is reported.
function bar(func = () = >foo) {
let foo = 'inner';
console.log(func());
}
bar() // ReferenceError: foo is not defined Copy the code
In the code above, foo in the anonymous function refers to the outer layer of the function, but the outer layer of the function does not declare the variable foo, so an error is reported.
Here is a more complicated example.
var x = 1;
function foo(x, y = function() { x = 2; {}) var x = 3;
y();
console.log(x);
} foo() / / 3 x / / 1 Copy the code
In the code above, the arguments to function foo form a single scope. In this scope, we first declare the variable x, then we declare the variable y, and the default value of y is an anonymous function.
The variable x inside this anonymous function points to the first parameter x of the same scope. The internal variable x is declared inside the function foo. This variable is not the same as the first parameter x because it is not in the same scope. Therefore, the internal variable x and the external global variable x are not changed after y.
If var x = 3 is removed, foo’s internal variable x points to the first argument x, which is the same as the anonymous function’s internal x, so the final output is 2, while the outer global variable x remains intact.
var x = 1;
function foo(x, y = function() { x = 2; {}) x = 3;
y();
console.log(x);
} foo() / / 2 x / / 1 Copy the code
Rest parameters
Basic instructions
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.
Use case
Based on the case
The add function is a summation function that can be passed any number of arguments using the REST argument.
function add(. values) {
let sum = 0;
for (var val of values) {
sum += val;
} return sum; } add(2.5.3) / / 10 Copy the code
The rest argument replaces the arguments variable
// arguments
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// The rest argument const sortNumbers = (. numbers) = > numbers.sort(); Copy the code
Comparing the two ways of writing the code above, you can see that the rest parameter is written more naturally and concisely.
The Arguments object is not an array, but an array-like object. So, in order to use an Array, the method of Array must be used. The prototype. Slice. Call it first into an Array.
The rest argument overwrites the array push method
const {log,error} = console;
function push(array, ... items) {
items.forEach(function(item) {
array.push(item);
});
return array; } var a = []; log(push(a, 1.2.3))/ / [1, 2, 3] Copy the code
Matters needing attention
Function length distortion
The REST parameter also does not count toward the Length attribute.
(function(a) {}).length / / 1
(function(. a) {}).length / / 0
(function(a, ... b) {}).length / / 1
Copy the code
Rest parameters cannot be followed by other parameters
The rest parameter cannot be followed by any other parameter (that is, only the last parameter), otherwise an error will be reported.
// Uncaught SyntaxError: Rest parameter must be last formal parameter
function f(a, ... b, c) {
// ...
}
Copy the code
The trailing comma of a function argument
ES2017 allows the trailing comma as the last argument to a function.
Previously, functions were defined and called without allowing a comma after the last argument.
function clownsEverywhere(
param1,
param2
) { / *... * / }
clownsEverywhere( 'foo'. 'bar' ); Copy the code
In the code above, if you put a comma after param2 or bar, you get an error.
If you want to add a third parameter to clownsEverywhere or reorder the parameters, add a comma after the last parameter if you want to add a third parameter to clownsEverywhere.
This to the version management system shows that the line where the comma was added has also changed. This seems a bit redundant, so the new syntax allows definitions and calls to end with a comma.
function clownsEverywhere(
param1,
param2,
) { / *... * / }
clownsEverywhere( 'foo'. 'bar'.); Copy the code
This also makes function arguments consistent with the trailing comma rule for arrays and objects.
Summary of today’s lesson
Today the mood
Function () function () function () function () function ()
I have seen deconstruction assignment for two consecutive days. I hope to learn ~~~~ tomorrow
This article is formatted using MDNICE