search
HomeWeb Front-endJS TutorialHow to operate the default parameters of processing functions in ES5 and ES6 environments

This time I will show you how to operate the default parameters of the processing function in the ES5 and ES6 environments. What are the precautions for operating the default parameters of the processing functions in the ES5 and ES6 environments. The following is a practical case, let's take a look. take a look.

The default value of the function is something that greatly improves the robustness (that is, it makes the program more robust)

MDN's description of the default parameters of the function: The default parameter of the function allows to be passed without a value or undefined Use the default parameters when entering.

ES5

Use logical OR || to achieve

As we all know, in the ES5 version, there is no direct method for us to deal with the default value of the function

So we can only enhance the function of the function ourselves, which is usually done like this:

function doSomething (name, age) {
 name = name || 'default name'
 age = age || 18
 console.log(name, age)
}
We will The two parameters name and age are processed as default values. If not,

uses the default value.

After executing the function, there seems to be nothing wrong:

doSomething()    // default name, 18
doSomething('Niko') // Niko    , 18
doSomething(, 12)  // default name, 12
However, when we execute such code, we will get some unexpected results:

doSomething('Niko', 0) // Niko, 18
It can be found that for parameter 0, our default parameter implementation method above is problematic.

Just like the four

expressions below, they will all output wrong, which obviously cannot satisfy the above requirements. MDN’s definition of function default parameters:

console.log(0     || 'wrong')
console.log(''    || 'wrong')
console.log(null   || 'wrong')
console.log(false   || 'wrong')

Correct posture

So, the correct default value processing in ES5 should be like this:

function doSomething (name, age) {
 if (name === undefined) {
  name = 'default name'
 }
 if (age === undefined) {
  age = 18
 }
 console.log(name, age)
}
Use the

ternary operator operator to simplify the operation

Or we can shorten it to the ternary operator form:

function doSomething (name, age) {
 name = name === undefined ? 'default name' : name
 age = age === undefined ? 18       : age
 console.log(name, age)
}

Use functions for encapsulation

But if we have to repeat these operations every time we write a function

It would be too troublesome, so we This logic is simply encapsulated:

function defaultValue (val, defaultVal) {
 return val === undefined ? defaultVal : val
}
function doSomething (name, age) {
 name = defaultValue(name, 'default name')
 age = defaultValue(age , 18)
 console.log(name, age)
}
In this way, the logic of the default parameters of the function is very concisely implemented in ES5

one momre things

About the implementation of the defaultValue function above Method, after we reasonably use the advantages of weakly typed languages

we can use this method to save the operation of the ternary operator:

function defaultValue () {
 return arguments[+(arguments[0] === undefined)]
}
We know that arguments represent all the actual parameters of the function

We use arguments[0] to get the first actual parameter, and then perform a congruent comparison with undefined

Convert the result of the expression to Number in the outer layer, and then use this value as a subscript to get arguments corresponding parameters.

Because it is converted from Boolean value, there are only two options: 0 and 1.

This also realizes the function of the ternary operator above.

ES6

The default value of the function in the ES6 version is basically the routine we implemented above

But because It is native, so there will be corresponding new syntax, which can be used more concisely:

function doSomething (name = 'default name', age = 18) {
 console.log(name, age)
}
ES6 provides a new syntax that allows us to write = [defaultValue] directly after the function declaration parameters. form to set the default value of a parameter.

Using this method directly eliminates the need to check the default value inside the function, allowing the function to focus on doing what it should do.

How to throw exceptions for certain required parameters

This new syntax of ES6 allows us to Error reminder for a required parameter:

function requireParams () {
 throw new Error('required params')
}
function doSomething (name = requireParams(), age = 18) {
 // do something
}
If the name parameter is undefined, the default value rule will be triggered

Then the requireParams function is called, and we directly throw one in the function Error

Default value processing of complex structure parameters

The above processing is for simple basic type data, but if we There is a function as follows:

function init ({id, value}) {}
init({
 id: 'tagId',
 value: 1
})

如果在ES5环境下,针对这种参数的默认值处理将会变得无比复杂

首先要判断这一个参数是否存在,然后在判断参数中的所有key是否存在

而在ES6中,可以这样来做:

function init ({
 id  = 'defaultId',
 value = 1
} = {}) {
 console.log(id, value)
}
init()

首先在解构函数的后边添加默认值= {},然后针对每一项参数添加默认值,很简洁的就实现了我们的需求。

ES5版本的polyfill代码在仓库中的位置:defaultValue

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样优化js async函数

如何使用node搭建服务器,写接口,调接口,跨域

The above is the detailed content of How to operate the default parameters of processing functions in ES5 and ES6 environments. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment