7
Translator: Frontend Xiaozhi
Author: Tania Rascia
Source: flatlogic.com

Are dreaming, dry, micro-channel search [World] big move concerned about this in the morning still in the dishwashing dishwashing wisdom.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line factory interview complete test sites, materials and my series of articles.

I’m Xiaozhi, today, let’s talk about the default parameters.

In ES6, JS introduced default function parameters. If no actual parameters are provided to the function call, the developer is allowed to initialize the function with default values. Initializing function parameters in this way will make the function easier to read, less error-prone, and provide default behavior for the function. This also helps us avoid errors caused by passing in undefined parameters and deconstructing non-existent objects.

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

Actual and formal parameters

Before explaining the default function parameters, it is important to know what the default value of the parameter is. So let's review the difference between actual and formal parameters in a function.

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

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

x variable in this example is a parameter-a named variable passed to the function, and the parameter must always be contained 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 it is called. Usually, the value can also be a variable, such as:

const number = 10

cube(number) // 1000

If no parameters are passed to the function, the function will implicitly use undefined as the default value:

cube() // NaN

In the present embodiment, cube() tried to calculate undefined * undefined * undefined value, the result is NaN .

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

Default parameter syntax

If there is no default parameter, we need to explicitly check 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()

On the contrary, using default parameters can achieve the same goal with less code. You can set default values for the parameters in the cube by using the equality assignment operator ( =

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

Now, calling the cube function without arguments, it is x Fu 5 and return calculation instead NaN :

When the parameters are passed, it will still behave as expected, ignoring the default values:

cube(2)  // 8

One thing to note is that the default parameter value will also overwrite undefined passed as a parameter of the function, as shown below:

cube(undefined)  // 125

Here is calculated using the default parameter 5 , the displayed transmission undefined will be ignored.

Default parameter data type

Any original value or object can be used as the default parameter value. First, use number , string , boolean , object , array and null as default values to set the parameters.

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 parameters, they will all use default values:

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

Note that any objects created in the default parameters will be created every time the function is called. A common use case for default parameters is to use this behavior to get a value from an object. If we try to deconstruct or access a value from a non-existent object, it will throw an error. However, if the default parameter is an empty object, then it will only give undefined without throwing an error.

function settings(options = {}) {
  const { theme, debug } = options

  // Do something with settings
}

This avoids errors caused by deconstructing non-existent objects.

Now that we have seen how the 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 function sum()

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 creates a user object userObj as the third parameter, what the function itself does is return userObj and the first two parameters

function createUser(name, rank, userObj = { name, rank }) {
  return userObj
}

// Create user
const user = createUser('前端小智', '前端开发')

console.log(user) // {name: "前端小智", rank: "前端开发"}

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

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

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

efaultFirst(undefined, 2)  // 3

In actual combat, the following is a function, its role is to create a DOM element, and add a text label and class (if it exists).

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('p', 'Hello!', ['greeting', 'active'])

At this time, the value of greeting

<p class="greeting active">Hello!</p>

If you keep the classNames array out of the function call, the array will still work.

const greeting2 = createNewElement('p', 'Hello!')

console.log(greeting2) // p>Hello!</p>

Function call as default parameter

In addition to primitive types and objects, the results of calling functions can be used as default parameters.

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 * x
}

Now every time you call cube result may be different:

cube()  // 512
cube()  // 64

In the following example, a random number is assigned to x , which is used as a parameter in our creation function. Then, the y parameter will calculate the cube root of the number and check 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, it defines the parameter as an internal function and returns a function call:

function outer(
  parameter = function inner() {
    return 100
  }
) {
  return parameter()
}

// Invoke outer function
outer() // 100

Summarize

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

This is Xiaozhi, see you next time!


possible bugs in 161034811003ec editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

Original: https://www.taniarascia.com/default-parameters-javascript/

comminicate

The article is continuously updated every week. You can search for [Great Move to the World] Read it for the first time and reply to [Welfare] are multiple front-end videos waiting for you. This article GitHub https://github.com/qq449245884/xiaozhi has been included, welcome to Star.


王大冶
68k 声望104.9k 粉丝