Explore the rest parameter and parameter default values in JavaScript basics

Source: Internet
Author: User
Tags readable

Rest parameters

In general, we need to create a function with variable parameters, which means that a 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 function of variable parameters.

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

The following are the traditional ways to implement

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 argument list when the function is invoked. This code is exactly what we want, but its readability is not optimal. A function has only one formal parameter haystack, so it is impossible to see that the function requires multiple parameters, and when traversing arguments, it is necessary to pay special attention to the start index of the traversal as 1 rather than the usual 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 internal loop. The rest parameters address these issues, and the following are implementations that use the rest parameter:

function Containsall (haystack, ... needles) {for 
 (var needle of needles) { 
 if (haystack.indexof (needle) = = 1) { C3/>return false; 
 } 
 } 
 return true; 
} 
  
function Containsall (haystack, ... needles) {for 
 (var needle of needles) { 
 if (haystack.indexof (needle) = = 1) { return 
  false; 
 } 
 } 
 return true; 

All two implementations meet our needs, but the latter contains a special ... needles syntax. Let's look at the details of the call to Containsall ("banana", "B", "Nan"), and the arguments haystack, as ever, will be filled with the first argument of the function, the value is "banana", and the previous ellipsis in 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 the Needles is ["B", "Nan"]. Then, the normal function is executed.

You can only use the last function of a function as a Rest parameter. When a function is invoked, the parameters before the rest parameter are filled in properly, the arguments outside 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 rest parameter's value is an empty array [], The value of the Rest parameter will never be undefined.

Default values for parameters

Typically, when a function is invoked, the caller is not required to pass all possible arguments, and the arguments that are not passed require a reasonable default value. JavaScript has a fixed default value undefined for parameters that are not passed. In ES6, a new method is introduced to specify the default values 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 ") returns" lions and elephants and bears! Oh my! ", Animalsentence (" Elephants "," whales ") returns" lions and elephants and whales! Oh my! ".

A few details to note for the default value of a parameter:

Unlike Python, the expression of a parameter default value is computed from left to right when the function is called, which means that the expression can use a parameter that has been previously 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") returns "lions and bears and sealions." Oh my! ".

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

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

Copy Code code as follows:
function MyFunc (a=42, b) {...}

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

Equal to

Copy Code code as follows:
function MyFunc (a=42, b=undefined) {...}

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

Abandon arguments

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

It is hoped that the above two new features will completely replace arguments. As a first step, avoid using the arguments object when you use the rest parameter or the default value of the parameter, and if the arguments object is not immediately removed or never, it is also best to avoid using the arguments object when you use the rest parameter or the default value of the parameter.

Compatibility

The Firefox 15 version already supports these two new features. However, in addition, there is no other browser support. Recently, V8 's experimental environment has added support for rest parameters, while the parameter defaults also have a ISSUE,JSC that also introduces some issue to rest parameters and parameter defaults.

Babel and Traceur both compilers have supported parameter defaults, so you can use them boldly.

Conclusion

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

The above is the entire content of this article, I hope to help you learn.

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.