Study the rest parameters and parameter defaults in JavaScript

Source: Internet
Author: User

Study the rest parameters and parameter defaults in JavaScript


This article discusses two features that make JavaScript functions more expressive: The Rest parameter and the default value of the parameter.

Rest Parameters

In general, we need to create a variable parameter function, which means that the function can accept any number of arguments. For example, String.prototype.concat can accept any number of strings as arguments. Using the Rest parameter, ES6 provides us with a new way to create a variable-parameter function.

Let's implement an example function, Containsall, to check whether a string contains some substrings. For example, Containsall ("Banana", "B", "Nan") will return True,containsall ("Banana", "C", "Nan") will return false.

The following are the traditional implementations (ref.: http://www.aichengxu.com/view/62895):

function Containsall (haystack) {for (var i = 1; i < arguments.length; i++) {  var needle = arguments[i];  if (haystack.indexof (needle) = =-1) {   return false;  }} return True,} function Containsall (haystack) {for (Var i = 1; i < arguments.length; i++) {  var needle = arguments[i];  if (haystack.indexof (needle) = = =-1) {   return false;  }} return true;}


The implementation uses the arguments object, which is a class array object that contains the list of arguments when the function is called. This code is exactly what we want, but its readability is not optimal. The function has only one parameter haystack, so it is not possible to know that the function requires multiple parameters at a glance, and when traversing arguments, it is important to pay special attention to the start index of the traversal as 1, rather than the common 0, because Arguments[0] is the formal parameter haystack when the function is defined. If we want to add some parameters before or after the haystack parameter, we have to update the inner loop. The rest parameter solves these problems, and here's how to use the rest parameter:

Http://www.aichengxu.comfunction containsall (haystack, ... needles) {for (var needle of needles) {  if ( Haystack.indexof (needle) = =-1) {   return false;  }} return true;} function Containsall (haystack, ... needles) {fo R (Var needle of needles) {  if (haystack.indexof (needle) = = = 1) {   return false;  }} return true;}


The above two implementations meet our needs, but the latter contains a special ... needles syntax. Let's take a look at the details of calling Containsall ("banana", "B", "Nan"), the parameter haystack, as usual, will be populated with the first argument of the function, the value is "banana", and the ellipsis in front of the needles indicates that it is a Rest parameter, All remaining real arguments are placed in an array and assigned to the needles. In this call, the value of needles is ["B", "Nan"]. Then, the normal function is executed.

Only the last function of the function can be used as the rest parameter, and when the function is called, the parameters before the Rest parameter are filled normally, the parameters are placed in an array, and the array is used as the value of the rest parameter, and if there are no more arguments, the value of the rest parameter is an empty array [], The value of the Rest parameter will never be undefined.

default values for parameters

Typically, when a function is called, the caller is not required to pass all possible arguments, and those parameters that are not passed require a reasonable default value. JavaScript has a fixed default value of undefined for those parameters that are not passed. In ES6, a new method is introduced to specify the default value for any parameter.

Look at the following example:

function animalsentence (animals2= "tigers", animals3= "bears") {  return ' Lions and ${ANIMALS2} and ${animals3}! Oh my! ';} function animalsentence (animals2= "tigers", animals3= "bears") {  return ' Lions and ${ANIMALS2} and ${animals3}! Oh my! ';}


After the = of each parameter is an expression that specifies the default value when the parameter is not passed. So, animalsentence () returns "Lions and tigers and bears! Oh my! ", Animalsentence (" Elephants ") return" Lions and elephants and bears! Oh my! ", Animalsentence (" Elephants "," whales ") return" Lions and elephants and whales! Oh my!. "

A few details to note about the default value of the parameter:

Unlike Python, an expression of the default value of a parameter is evaluated from left to right when the function is called, which means that the expression can use the parameters that were already populated. For example, we can make the above function a little more interesting:

function animalsentencefancy (animals2= "tigers",  animals3= (animals2 = = "bears")? "Sealions": "Bears") {return ' Lions and ${ANIMALS2} and ${animals3}! Oh my! ';} function animalsentencefancy (animals2= "tigers",  animals3= (animals2 = = "bears")? "Sealions": "Bears") {return ' Lions and ${ANIMALS2} and ${animals3}! Oh my! ';}


Then, animalsentencefancy ("Bears") will return "Lions and Bears and sealions. Oh my!. "

Passing undefined is equivalent to not passing the parameter. Therefore, animalsentence (undefined, "unicorns") will return "Lions and tigers and unicorns! Oh my!. "

If you do not specify a default value for a parameter, the default value for this parameter is undefined, so

function MyFunc (a=42, b) {...} function MyFunc (a=42, b) {...}


Equivalent to

function MyFunc (a=42, b=undefined) {...} function MyFunc (a=42, b=undefined) {...}


Abandon Arguments

By using the default values for Rest parameters and parameters, we can completely discard the arguments object, making our code more readable. In addition, the arguments object also deepens the challenge of optimizing JavaScript.

I hope the above two new features can completely replace arguments. As a first step, avoid using the arguments object when using the default value of the rest parameter or parameter, if the arguments object is not immediately removed, or never, it is best to avoid using the arguments object when using the rest parameter or parameter defaults.

compatibility

More than 15 versions of Firefox already support these two new features. In addition, however, there is no other browser support. Recently, V8 's experimental environment added support for rest parameters, and a ISSUE,JSC with parameter defaults also raised some issue for rest parameters and parameter defaults.

Babel and Traceur both compilers already support parameter defaults, so you can use them boldly.

Conclusion

Although technically, these two new features do not introduce new behavior into the function, but they can make the declarations of some functions more expressive and readable.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Study the rest parameters and parameter defaults in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.