1. Default values of function parameters
es5 writing:
function log(x, y) {
if(typeof y=== "undefined"){ y = 'World' ;
} console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello
es6 writing:
1.function log(x, y = 'World') { console.log(x, y); } log('Hello') // Hello World log('Hello', 'China') // Hello China log('Hello', '') // Hello
2.function Point(x = 0, y = 0) { this.x = x; this.y = y; } const p = new Point(); p // { x: 0, y: 0 }
Parameters declared by default cannot be declared again with let or const.
function foo(x = 5) { let x = 1; // error const x = 2; // error }
When using parameter defaults, functions cannot have parameters with the same name.
// no error function foo(x, x, y) { // ... } // 报错 function foo(x, x, y = 1) { // ... } // SyntaxError: Duplicate parameter name not allowed in this context
Parameter default values are lazily evaluated.
let x = 99; function foo(p = x + 1) { console.log(p); } foo() // 100 x = 100; foo() // 101
Summary: 4 major characteristics of function default values.
1. The parameter directly uses the default value without further judgment.
2. After using the default value of the parameter, let and const declarations can no longer be used.
3. Use the parameter default value and cannot have duplicate parameters.
4. The parameter default value is lazy evaluation, and the value of the default value expression is recalculated every time.
Two: Use in conjunction with structure assignment defaults
1. The following code is a simple structure assignment, and does not use the default value.
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
If foo
no parameters are provided when the function is called, it is directly foo(); an error will be reported.
function foo({x, y = 5} = {}) { console.log(x, y); } foo() // undefined 5
The above code parameters use destructuring assignment, and use the default value. So there will be no error.
Conclusion: Whether destructuring assignment is an object, an array, or a string, as long as the default value is not used, then the calling function will report an error if the default parameter is not passed.