Home > Web Front-end > JS Tutorial > body text

Introduction to how to set default values ​​for JavaScript function parameters

不言
Release: 2018-11-12 16:26:47
forward
3027 people have browsed it

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);
Copy after login

Introduction to how to set default values ​​for JavaScript function parameters

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});
Copy after login

This writing method can be written out of order when passing in multiple formal parametersEnter, 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});
Copy after login

Introduction to how to set default values ​​for JavaScript function parameters

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template