


In-depth study of Rest parameters and parameter default values in JavaScript_Basic knowledge
This article will discuss two features that make JavaScript functions more expressive: Rest parameters and parameter default values.
Rest parameters
Usually, we need to create a function with variable parameters. Variable parameters means that the function can accept any number of parameters. For example, String.prototype.concat can accept any number of strings as arguments. Using Rest parameters, ES6 provides us with a new way to create variadic functions.
Let’s implement a sample function containsAll to check whether a string contains certain substrings. For example, containsAll("banana", "b", "nan") will return true and containsAll("banana", "c", "nan") will return false.
The following is the traditional implementation:
function containsAll(haystack) { for (var i = 1; i < arguments.length; i++) { var needle = arguments[i]; if (haystack.indexOf(needle) === -1) { return false; } } return true; } function containsAll(haystack) { for (var i = 1; i < arguments.length; i++) { var needle = arguments[i]; if (haystack.indexOf(needle) === -1) { return false; } } return true; }
This implementation uses the arguments object, which is an array-like object that contains the actual parameter list when the function is called. This code is exactly what we want, but its readability is not optimal. The function has only one formal parameter haystack, so it is impossible to know at a glance that the function requires multiple parameters. When traversing arguments, you need to pay special attention to the starting index of the traversal being 1 instead of the common 0, because arguments[0] is the function The formal parameter haystack when defined. If we want to add some parameters before or after the haystack parameter, we have to update the inner loop. Rest parameters solve these problems. Here is how to use Rest parameters:
function containsAll(haystack, ...needles) { for (var needle of needles) { if (haystack.indexOf(needle) === -1) { return false; } } return true; } function containsAll(haystack, ...needles) { for (var needle of needles) { if (haystack.indexOf(needle) === -1) { return false; } } return true; }
Both of the above implementations meet our needs, but the latter contains a special ...needles syntax. Let's take a look at the details when calling containsAll("banana", "b", "nan"). The parameter haystack will be filled with the first argument of the function as usual, with the value "banana" and the ellipses in front of needsles. Indicates that it is a Rest parameter, all remaining actual parameters will be put into an array, and the array will be assigned to the needs iteration. In this call, the value of needs is ["b", "nan"]. Then, the normal function is executed.
Only the last function of the function can be used as a Rest parameter. When the function is called, the parameters before the Rest parameter will be filled in normally, and the other parameters will be put into an array, and the array will be used as Rest The value of the parameter. If there are no more parameters, then the value of the Rest parameter is an empty array []. The value of the Rest parameter will never be undefined.
Default value of parameter
Usually, when calling a function, the caller does not need to pass all possible parameters, and those parameters that are not passed need a reasonable default value. JavaScript has a fixed default value of undefined for parameters that are not passed. In ES6, a new way to specify default values for arbitrary parameters was introduced.
Look at the example below:
function animalSentence(animals2="tigers", animals3="bears") { return `Lions and ${animals2} and ${animals3}! Oh my!`; } function animalSentence(animals2="tigers", animals3="bears") { return `Lions and ${animals2} and ${animals3}! Oh my!`; }
After = for each parameter there is an expression that specifies the default value when the parameter is not passed. So, animalSentence() returns "Lions and tigers and bears! Oh my!", animalSentence("elephants") returns "Lions and elephants and bears! Oh my!", animalSentence("elephants", "whales") returns "Lions and elephants and whales! Oh my!".
A few details to note about parameter default values:
Unlike Python, expressions for parameter default values are evaluated from left to right when the function is called, which means that the expression can use parameters that have been filled in previously. For example, we could make the function above a little more interesting:
function animalSentenceFancy(animals2="tigers", animals3=(animals2 == "bears") ? "sealions" : "bears") { return `Lions and ${animals2} and ${animals3}! Oh my!`; } function animalSentenceFancy(animals2="tigers", animals3=(animals2 == "bears") ? "sealions" : "bears") { return `Lions and ${animals2} and ${animals3}! Oh my!`; }
Then, animalSentenceFancy("bears") will return "Lions and bears and sealions. Oh my!".
Passing undefined is equivalent to not passing the parameter. Therefore, animalSentence(undefined, "unicorns") will return "Lions and tigers and unicorns! Oh my!".
If no default value is specified for a parameter, the default value of the parameter is undefined, so
function myFunc(a=42, b) {...} function myFunc(a=42, b) {...}
is equivalent to
function myFunc(a=42, b=undefined) {...} function myFunc(a=42, b=undefined) {...}
Discard arguments
With Rest parameters and default values for parameters, we can ditch the arguments object entirely, making our code more readable. Additionally, the arguments object adds to the difficulty of optimizing JavaScript.
Hopefully the above two new features can completely replace arguments. As a first step, avoid using arguments objects when using Rest parameters or parameter default values. If the arguments object will not be removed immediately, or never, then it is also best to avoid using Rest parameters or parameters. The default is to use the arguments object.
Compatibility
Firefox 15 or above already supports these two new features. However, beyond that, there is no other browser support. Recently, V8's experimental environment has added support for Rest parameters, and there is an issue with parameter default values. JSC has also raised some issues with Rest parameters and parameter default values.
Both compilers, Babel and Traceur, already support parameter default values, so you can use them boldly.
Conclusion
Although technically these two new features do not introduce new behavior to functions, they can make some function declarations more expressive and readable.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
