javascript-function Parameters: Default parameters and Remaining parameters __ block chain

Source: Internet
Author: User
function arguments (functions parameter) EDIT

Starting with ECMAScript 6, there are two new types of parameters: default parameters, remaining parameters (rest parameters). default parameter (parameter)

In JavaScript, the default value for a function parameter is undefined. However, it is useful to set different default values in some cases. The default parameters are available to help.

In the past, the general policy for setting the default was to give a value if the principal test parameter value for the function was undefined. If, in the following example, the function is called without an argument passed to B, its value is undefined, so the a*b is computed and the function returns NaN:

function Multiply (A, b) {
  b = typeof b!== ' undefined '?  b:1;

  return a*b;
}

Multiply (5); 5

Using default parameters, the check in the function body is no longer needed. Now, you can simply set 1 to the default value of B in the function header:

function Multiply (A, b = 1) {return
  a*b;
}

Multiply (5); 5
remaining parameters (rest parameters)

The remaining parameter syntax allows an indeterminate number of arguments to be represented as an array. In the following example, the remaining parameters are used to collect from the second to the last parameter. Then, we multiply each number of this array by the first argument. This example uses an arrow function, which is described in the next section.

function multiply (multiplier, ... theargs) {return
  theargs.map (x => multiplier * x);
}

var arr = Multiply (2, 1, 2, 3);
Console.log (arr); [2, 4, 6]
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.