This article brings you an introduction to the method of setting the default value of JavaScript function parameters. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The default value setting of the function is given in ES6. Here is a brief introduction to several methods of setting default parameters
1. Basic usage
function first(x = 1, y = 2) { console.log("x:"+x ,"y:"+ y); } first(); first(100);
2. Combined with the default value of destructuring assignment
function second({x, y = 2}) { console.log("x:"+x ,"y:"+ y); } second({}); second({x:100}); second({x:100,y:200});
This writing method can be written out of order when passing in multiple formal parameters
Enter, it will be much more convenient, but there will be a problem. It will be very troublesome to pass "{}" every time, so we can set the default value again
3. Double default Value
function third({x = 1 ,y = 2} = {}) { console.log("x:"+x ,"y:"+ y); } third(); third({x:100,y:200}); third({x:100});
This way of writing will not be error-prone
4. Summary
You should use the default value settings when encapsulating functions in the future, especially some multi-parameter functions
The above is the detailed content of Introduction to how to set default values for JavaScript function parameters. For more information, please follow other related articles on the PHP Chinese website!