Home Web Front-end JS Tutorial ECMAScript6 function default parameters_javascript tips

ECMAScript6 function default parameters_javascript tips

May 16, 2016 pm 03:55 PM
Default parameters

Every new feature added during the language update is extracted from the needs of millions of developers. Standard adoption can reduce the pain of programmers and bring convenience.

We often write like this

function calc(x, y) {
  x = x || 0;
  y = y || 0;
  // to do with x, y
  // return x/y
}
Copy after login

To put it simply, x and y provide a default value of 0. When not passed, x and y are calculated with the value 0. Once passed, the actual value will be used for calculation.

Another example is defining an ajax

function ajax(url, async, dataType) {
  async = async !== false
  dataType = dataType || 'JSON'
  // ...
}
Copy after login

A simple ajax function encapsulated with native JS. The url is required, async and dataType are optional. If not filled in, the default is to request and return JSON format data synchronously.

Another example is defining a rectangle class

function Rectangle(width, height) {
  this.width = width || 200;
  this.height = height || 300;
}
Copy after login

Without passing any parameters when new, a rectangle with a default width and height of 200*300 will be created.

Whether it is calc, ajax function or Rectangle class, we all need to handle the default value in the function body. Wouldn’t it be nice if the language handles it by itself? ES6 provides this feature (Default Parameters). The following are calc, ajax, and Rectangle rewritten with the new features of ES6.

function calc(x=0, y=0) {
  // ...
  console.log(x, y)
}
calc(); // 0 0
calc(1, 4); // 1 4
 
function ajax(url, async=true, dataType="JSON") {
  // ...
  console.log(url, async, dataType)
}
ajax('../user.action'); // ../user.action true JSON
ajax('../user.action', false); // ../user.action false JSON
ajax('../user.action', false, 'XML'); // ../user.action false XML
 
function Rectangle(width=200, height=300) {
  this.width = width;
  this.height = height;
}
var r1 = new Rectangle(); // 200*300的矩形
var r2 = new Rectangle(100); // 100*300的矩形
var r3 = new Rectangle(100, 500); // 100*500矩形
Copy after login

As you can see, ES6 moved the default value part from braces to parentheses, and also reduced the "||" operation, and the function body has since been slimmed down. The default value of the parameter should be in the place where the parameter is defined, which looks a lot simpler. O(∩_∩)O

Default parameters can be defined at any position, such as defining a

in the middle
function ajax(url, async=true, success) {
  // ...
  console.log(url, async, success)
}
Copy after login

defines a default parameter async, url and success are required. In this case, you need to set the middle parameter to undefined

ajax('../user.action', undefined, function() {
   
})
Copy after login

Note, don’t take it for granted and change undefined to null. Even if null == undefined, after passing null, the async in the function body will be null and not true.

The following points need to be noted:

1. After defining the default parameters, the length attribute of the function will be reduced, that is, several default parameters are not included in the calculation of length

function calc(x=0, y=0) {
  // ...
  console.log(x, y)
}
function ajax(url, async=true, dataType="JSON") {
  // ...
  console.log(url, async, dataType)
}
console.log(calc.length); // 0
console.log(ajax.length); // 1

Copy after login

2. Let and const cannot be used to declare the default value again, var can be

function ajax(url="../user.action", async=true, success) {
  var url = ''; // 允许
  let async = 3; // 报错
  const success = function(){}; // 报错
}

Copy after login

Another interesting thing is: the default parameter can not be a value type, it can be a function call

function getCallback() {
  return function() {
    // return code
  }
}
 
function ajax(url, async, success=getCallback()) {
  // ...
  console.log(url, async, success)
}
Copy after login

You can see that the parameter success here is a function call. If the third parameter is not passed when calling ajax, the getCallback function will be executed, which returns a new function assigned to success. This is a very powerful function that gives programmers a lot of room for imagination.

For example, you can use this feature to force a certain parameter to be passed, otherwise an error will be reported

function throwIf() {
  throw new Error('少传了参数');
}
 
function ajax(url=throwIf(), async=true, success) {
  return url;
}
ajax(); // Error: 少传了参数
Copy after login

The above is the entire content of this article, I hope you all like it.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Default parameters in C++ function declarations: a comprehensive analysis of their declaration and usage Default parameters in C++ function declarations: a comprehensive analysis of their declaration and usage May 02, 2024 pm 03:09 PM

Default parameters in C++ provide the ability to specify default values ​​for function parameters, thereby enhancing code readability, simplicity, and flexibility. Declare default parameters: Add the "=" symbol after the parameter in the function declaration, followed by the default value. Usage: When the function is called, if optional parameters are not provided, the default values ​​will be used. Practical case: A function that calculates the sum of two numbers. One parameter is required and the other is optional and has a default value of 0. Advantages: Enhanced readability, increased flexibility, reduced boilerplate code. Note: It can only be specified in the declaration, it must be at the end, and the types must be compatible.

How to optimize the use of default parameters and variadic parameters in C++ functions How to optimize the use of default parameters and variadic parameters in C++ functions Apr 20, 2024 am 09:03 AM

Optimize C++ default and variable parameter functions: Default parameters: Allow functions to use default values, reducing redundancy. Put default parameters last to improve readability. Use constexpr default parameters to reduce overhead. Use structured binding to improve readability of complex default parameters. Variable parameters: allows a function to accept a variable number of parameters. Try to avoid using variadic arguments and use them only when necessary. Use std::initializer_list to optimize variadic functions to improve performance.

Usage and advantages of C++ default parameters Usage and advantages of C++ default parameters Apr 18, 2024 pm 09:33 PM

Yes, the default parameter feature in C++ allows you to omit certain parameters when a function is called. When the function is called and these parameters are not provided, the default values ​​​​are used, thereby improving the flexibility, readability and maintainability of the code. .

Things to note about default parameters in C++ functions Things to note about default parameters in C++ functions Apr 20, 2024 am 11:09 AM

Note that default parameters in C++ functions must appear at the end of the parameter list. Multiple default values ​​cannot be specified for the same parameter. vararg variable number of parameters cannot have default values. Default parameters cannot be shared by parameters of overloaded functions.

The Magical Use of PHP Default Parameters: The Secret to Improving Code Efficiency The Magical Use of PHP Default Parameters: The Secret to Improving Code Efficiency Mar 24, 2024 am 10:33 AM

PHP is a widely used server-side scripting language for developing dynamic web pages and applications. In PHP, using default parameters can greatly improve the efficiency and simplicity of your code. This article will explore how to take advantage of PHP's default parameter function to achieve more efficient programming. 1. The concept of default parameters In PHP functions, we can set default values ​​for parameters. When a function is called without providing a parameter value, the default value will be used instead. Doing so can simplify function calls, reduce redundant code, and improve readability. 2.Default parameters

How to use default parameters of C++ functions? How to use default parameters of C++ functions? Apr 19, 2024 pm 03:21 PM

Default parameters allow functions to specify default values ​​when called, simplifying code and improving maintainability. The syntax of default parameters is: typefunction_name(parameter_list,typeparameter_name=default_value). Among them, type is the parameter type, parameter_name is the parameter name, and default_value is the default value. In the example, the add function has two parameters, of which the default value of num2 is 0. When calling the function, you can specify only num1 and num2 will use the default value, or specify both num1 and num2.

How does the parameter passing method of PHP functions handle optional parameters and default parameters? How does the parameter passing method of PHP functions handle optional parameters and default parameters? Apr 15, 2024 pm 09:51 PM

Parameter passing methods: passing by value (basic types) and passing by reference (composite types). Optional parameters: Parameter values ​​are allowed to be specified, but are not required. Default parameters: Allows specifying default values ​​for optional parameters. Practical combat: Demonstrate how to calculate the area of ​​a rectangle using optional and default parameters through an example function.

Analysis of usage scenarios of default parameters in C++ functions Analysis of usage scenarios of default parameters in C++ functions Apr 19, 2024 pm 06:12 PM

Default parameters are used to simplify function calls, provide optional functionality, and improve code readability. Specific scenarios include: 1. Omitting uncommon parameters; 2. Providing default values ​​for optional functions; 3. Explicitly specifying default values ​​to improve code understandability.

See all articles