Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write the default parameters in JavaScript

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces how to write the default parameters in JavaScript. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

In ES6, JS introduces default function parameters. If no arguments are provided to the function call, the developer is allowed to initialize the function with default values. Initializing function parameters in this way makes the function easier to read, less error-prone, and provides default behavior for the function. This also helps us avoid errors caused by passing in undefined parameters and deconstructing objects that do not exist.

In this article, we will learn the difference between formal parameters and arguments, learn how to use default parameters in functions, learn about other methods that support default parameters, and learn which types of values and expressions can be used as default parameters.

Actual parameter and formal parameter

Before interpreting the default function parameters, it is important to know what the default values of the parameters are. So let's first review the difference between arguments and formal parameters in the function.

In the following code, we create a function that returns the cube of a given number:

Function cube (x) {return x * x * x}

The x variable in this example is a parameter-a named variable passed to the function, and the parameter must always be included in the variable. Next, let's call this function:

Cube (10) / / 1000

In this case, 10 is a parameter-the value passed to the function when called. In general, values can also use variables, such as:

Const number = 10 cube (number) / / 1000

If the function is not passed an argument, the function implicitly uses undefined as the default value:

Cube () / / NaN

In this case, cube () attempts to calculate the value of undefined * undefined * undefined, and the result is NaN.

This automatic behavior can sometimes cause problems. In some cases, we want the parameter to have a value, even if it is not passed to the function. This is where the default parameter feature comes in handy.

Default parameter syntax

If there are no default parameters, we need to explicitly check the value of undefined to set the default value, as shown in the following example:

Function cube (x) {if (typeof x = = 'undefined') {x = 5} return x * x * x} cube ()

Instead, you can achieve the same goal with less code by using default parameters. You can set default values for parameters in the cube by using the equality assignment operator (=), as follows:

Function cube (x = 5) {return x * x * x}

Now, when the cube function is called without arguments, it assigns 5 to x and returns a calculation instead of NaN:

When you pass a parameter, it still works as expected, ignoring the default value:

Cube (2) / / 8

It is important to note that the default parameter value also overrides the undefined passed as an argument to the function, as shown below:

Cube (undefined) / / 125

This is calculated using the default parameter 5, and the displayed passing undefined is ignored.

Default parameter data type any original value or object can be used as the default parameter value. First, set the parameters using number, string,boolean,object, array, and null as default values.

Const defaultNumber = (number = 42) = > console.log (number) const defaultString = (string = 'Shark') = > console.log (string) const defaultBoolean = (boolean = true) = > console.log (boolean) const defaultObject = (object = {id: 7}) = > console.log (object) const defaultArray = (array = [1,2,3]) = > console.log (array) const defaultNull = (nullValue = null) = > console.log (nullValue)

When these functions are called without arguments, they all use default values:

DefaultNumber () / / 42 defaultString () / / "Shark" defaultBoolean () / / true defaultObject () / / {id: 7} defaultArray () / / (3) [1,2,3] defaultNull () / / null

Note that any object created in the default parameter will be created each time the function is called. A common use case for default parameters is to use this behavior to get values from objects. If we try to deconstruct or access a value from an object that does not exist, it will throw an error. However, if the default parameter is an empty object, it only gives the value of undefined and does not throw an error.

Function settings (options = {}) {const {theme, debug} = options / / Do something with settings}

This avoids errors caused by deconstructing objects that do not exist.

Now that we've seen how default parameters work with different data types, let's take a look at how multiple default parameters work together.

Use multiple default parameters

First, declare a sum () function with multiple default parameters

Function sum (a = 1, b = 2) {return a + b} sum () / / 3

In addition, the values used in the parameters can be used in any subsequent default parameters, from left to right. For example, this createUser function creates a user object userObj as the third argument, and all the function itself does is return userObj and the first two arguments

Function createUser (name, rank, userObj = {name, rank}) {return userObj} / / Create user const user = createUser ('front-end console.log', 'front-end development') console.log (user) / / {name: "front-end development", rank: "front-end development"}

It is generally recommended that all default parameters be placed at the end of the parameter list so that optional values can be easily retained. If you first use the default parameter, you must explicitly pass undefined to use the default value.

Function defaultFirst (a = 1, b) {return a + b}

When calling this function, you must call defaultFirst () with two parameters:

EfaultFirst (undefined, 2) / / 3

As a practical example, here is a function that creates a DOM element and adds a text label and class (if any).

Function createNewElement (tag, text, classNames = []) {const el = document.createElement (tag) el.textContent = text classNames.forEach ((className) = > {el.classList.add (className)}) return el} const greeting = createNewElement ('greeting',' active'])

At this point, the value of greeting is

Hello!

If you leave the classNames array outside the function call, the array will still work.

Const greeting2 = createNewElement ('packs,' Hellostones') Console.log (greeting2) / / p > Hello!

The result of a function call as a default parameter can be used as a default parameter except for the original type and object.

In the following code, create a function that returns a random number, and then use the result as the default parameter value in the cube function:

Function getRandomNumber () {return Math.floor (Math.random () * 10)} function cube (x = getRandomNumber ()) {return x * x}

Now the result may be different each time you call cube:

Cube () / 512 cube () / / 64

In the following example, a random number is assigned to x, which is used as a parameter in our created function. The y parameter then calculates the cube root of the number and checks whether x and y are equal:

Function doesXEqualY (x = getRandomNumber (), y = Math.cbrt (cube (x) {return x = = y} doesXEqualY () / / true

The default parameter can even be a function definition, as shown in this example, which defines the parameter as an internal function and returns a function call to the parameter:

Function outer (parameter = function inner () {return 100}) {return parameter ()} / / Invoke outer function outer () / / 100

In this article, we learned what default function parameters are and how to use them. Now, we can use default parameters to help keep the function clean and easy to read. You can also pre-assign empty objects and arrays to parameters to reduce complexity and lines of code when dealing with situations such as retrieving values from objects or traversing arrays.

On how to write the default parameters in JavaScript to share here, I hope the above content can be of some help to you, you can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report