If an argument is missing during a function call, the value of this parameter variable is undefined. Before ES6, there was no neat syntax for setting default values for missing arguments, but we could generally write code to solve for missing parameter defaults:

function myFunction(x, y, z) {
 x = x === undefined ? 1 : x;
 y = y === undefined ? 2 : y;
 z = z === undefined ? 3 : z;
 console.log(x, y, z); //Output "6 7 3"
 }
 myFunction(6.7);Copy the code

Is it a little bit more cumbersome to write this way? Isn’t the default setting intuitive?

In ES6, we can do this with a much cleaner syntax, and in this article you’ll learn:

  • Declare parameter defaults using ES6 syntax
  • Use undefined to pass parameters
  • Parameters of operation

This passage takes about 5 minutes to read

Declare parameter defaults using ES6 syntax

We can use ES6’s concise syntax to declare default values for function arguments as shown in the following example:

function myFunction(x = 1, y = 2, z = 3) {
 console.log(x, y, z); 
}
myFunction(6.7); // Outputs 6 7 3Copy the code

In the code example above, we passed the first two arguments in calling this function, so the default values of the arguments (x=1 and y=2) will be overwritten (x=6 and y=7). Since the third parameter is default, z takes the default value and will be 3.

Use undefined to pass parameters

If we want to use the default value for a specific parameter, we can use undefined to assign the value, as shown in the following code:

function myFunction(x = 1, y = 2, z = 3) {
   console.log(x, y, z); // Outputs "1 7 9"
 }
 myFunction(undefined.7.9);Copy the code

Isn’t it very simple, just use undefined, we can specify a specific parameter to use the default value.

Parameters of operation

In ES6, we can not only assign specific values to parameters by default, but also support the logical operation of parameters to assign values, as shown in the following code:

function myFunction(x = 1, y = 2, z = x + y) {
   console.log(x, y, z); // Output "6 7 13"
 }
 myFunction(6.7);Copy the code

In the code above, we pass only the first two arguments, the third argument defaults, and the third argument’s value defaults to be the sum of the first two arguments.

section

That’s all for today. When we develop common components for engineering applications, we need to expose interfaces for use. The friendliness of these interfaces is a big determinant of the quality of the component, and the completeness of parameter defaults (default values) also affects the friendliness of the interface, thanks to ES6 allowing us to set parameter defaults in such a brief syntax.

E6 related articles

ES6 Basics Let and scope

【ES6 basics 】 Const introduction

More exciting content, please pay attention to the wechat “front-end talent” public number!