search
HomeWeb Front-endJS TutorialDetailed explanation of the default parameters of processing functions in ES5 and ES6 environments

This time I will bring you a detailed explanation of the default parameters of the processing functions in the ES5 and ES6 environments. What are the precautions for the default parameters of the processing functions in the ES5 and ES6 environments. The following is a practical case. Let’s take a look. one time.

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中文网其它相关文章!

推荐阅读:

jQuery实现无缝轮播与左右点击步骤详解

nodejs更改项目端口号步骤详解

The above is the detailed content of Detailed explanation of 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's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools