Default Syntax of parameters in ES6 and default Syntax of es6 Parameters
Preface
In ES6, if the function parameter has no value or is undefined, the default function parameter allows initialization of the initial value to the default value. Let's take a look at the detailed introduction.
Syntax
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements}
Description
In JavaScript, the default function parameter is defined. However, it may be useful to set different default values in some cases. This is where the default parameter can help.
In the past, the general policy for setting default values was to test the parameter values in the function body. If they were undefined, a value was assigned. In the following example, if B does not provide a value during the call, its value is undefined. When a * B is evaluated and this multiplication is called, NaN is returned.
function multiply(a, b) {var b = (typeof b !== 'undefined') ? b : 1;return a*b;}multiply(5); // 5
Set the default parameter in ES6, and check the function body is unnecessary. Now, you can set the default value in the function header:
function multiply(a, b = 1) { return a*b;}multiply(5); // 5
Example
Passed undefined
In the second function call, even if the second parameter is explicitly set to undefined (although not null), the color parameter of this function has a default value.
function setBackgroundColor(element, color = 'rosybrown') { element.style.backgroundColor = color;}setBackgroundColor(someDiv); // color set to 'rosybrown'setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' toosetBackgroundColor(someDiv, 'blue'); // color set to 'blue'
Evaluate the call time
The default parameters are calculated during the call, so unlike in Python, a new object is created every time a function is called.
function append(value, array = []) {array.push(value);return array;}append(1); //[1]append(2); //[2], not [1, 2]
It is even suitable for functions and variables.
function callSomething(thing = something()) { return thing }function something(){ return "sth";}callSomething(); //sth
Default parameters can be provided to future default parameters
You can provide the following default parameters:
function singularAutoPlural(singular, plural = singular+"s", rallyingCry = plural + " ATTACK!!!") { return [singular, plural, rallyingCry ];}//["Gecko","Geckos", "Geckos ATTACK!!!"]singularAutoPlural("Gecko");//["Fox","Foxes", "Foxes ATTACK!!!"]singularAutoPlural("Fox","Foxes");//["Deer", "Deer", "Deer ... change."]singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully petition the government for positive change.")
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.