By Dmitri Pavlutin

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

A function is a piece of code that is held together to perform a specific task. Functions typically interact with the outside world using arguments. To write simple and efficient JS code, you must master function parameters.

In this article, I’ll use some interesting examples to explain all the features that JS must handle function arguments efficiently.

1. Function parameters

JS functions can take any number of arguments. Let’s define a function that takes 0, 1, and 2 parameters.

Function zero() {return 0; } function identity(param) {return param; Function sum(param1, param2) {return param1 + param2; } zero(); // => 0 identity(1); // => 1 sum(1, 2); / / = > 3Copy the code

The above three function calls pass in the same number of arguments as the function defines. Of course, when the number of parameters passed in is less than the number of parameters defined, JS allows us to do so, no error, missing will use undefined instead.

For example, let’s call sum() with one argument (it takes two arguments)

function sum(param1, param2) {
  console.log(param1); // 1
  console.log(param2); // undefined
  return param1 + param2;
}

sum(1); // => NaN
Copy the code

This function is called with only one argument :sum(1). So param1 has a value of 1, but the second parameter param2 is initialized with undefined.

The value of param1 + param2 is 1 + undefined, and the result is NaN.

If necessary, you can verify that the parameter is undefined and provide a default value.

function sum(param1, param2) { if (param2 === undefined) { param2 = 0; } return param1 + param2; } sum(1); / / = > 1Copy the code

Or better yet, use the default parameters. Let’s see.

2. Default parameters

The DEFAULT parameter feature of ES6 allows you to initialize parameters with default values. This is better and more concise than the method described above.

Then use the ES6 default parameter feature to default param2 to 0.

function sum(param1, param2 = 0) { console.log(param2); // => 0 return param1 + param2; } sum(1); // => 1 sum(1, undefined); / / = > 1Copy the code

Now if no second argument is passed, param2 defaults to 0.

Note that if undefined is set to the second argument sum(1, undefined), param2 will also be initialized to 0.

3. Deconstruct the metrics

One thing I particularly like about JAVASCRIPT function arguments is the deconstruction feature. Objects or arrays of inline parameters can be deconstructed. This feature makes it useful to extract some properties from the parameter object

function greet({ name }) { return `Hello, ${name}! `; } const person = {name: 'front'}; greet(person); // => 'Hello! 'Copy the code

{name} is the argument applied to object deconstruction.

You can also combine the default parameters:

Function greetWithDefault({name = 'anonymous'} = {}) {return' Hello, ${name}! `; } greetWithDefault(); // => 'Hello, anonymous! 'Copy the code

{name = ‘Unknown’} ={} Defaults to an empty object.

You can use all the capabilities that combine different types of deconstruction. For example, let’s use object and array destructuring for the same parameter.

function greeFirstPerson([{ name }]) { return `Hello, ${name}! `; } const persons = [{name: 'Wang Xiaozhi}, {name:' dazhi wang '}]. greeFirstPerson(persons); // => 'Hello, Wang Xiaozhi! 'Copy the code

The [{name}] deconstruction is more complex, extracting the first item of the array and then reading the name attribute from the object.

4. The arguments object

Another nice feature of JS functions is the ability to call the same function with mutable arguments. This lets you use the Arguments object to get all the arguments passed in.

Arguments objects are local variables available in all (non-arrow) functions. You can use arguments objects to refer to function arguments in functions.

For example, summing the parameters of a function:

function sumArgs() { console.log(arguments); // { 0: 5, 1: 6, length: 2 } let sum = 0; for (let i = 0; i < arguments.length; i++) { sum += arguments[i]; } return sum; } sumArgs(5, 6); / / = > 11Copy the code

Arguments is an array-like object corresponding to the arguments passed to the function.

One problem is that each function scope defines its own arguments object. Therefore, an additional variable may be needed to access arguments from the external function scope:

function outerFunction() {
  const outerArguments = arguments;
  return function innerFunction() {
    // outFunction arguments
    outerArguments[0];
  };
}
Copy the code

4.1 Arrow function

There is one special case: there is no arguments in the arrow w function.

const sumArgs = () => {
  console.log(arguments);
  return 0;
};

// throws: "Uncaught ReferenceError: arguments is not defined"
sumArgs();
Copy the code

But this question is not. You can make the remaining arguments access all of the arguments within the arrow function. To look look.

5. Remaining parameters

The residual argument syntax allows us to represent an indefinite number of arguments as an array.

Same old, see see.

function sumArgs(... numbers) { console.log(numbers); // [5, 6] return numbers.reduce((sum, number) => sum + number); } sumArgs(5, 6); / / = > 11Copy the code

. Numbers is a residual parameter that will become a true array of residual parameters [5,6]. Since numbers is an array, you can use the array’s own reduce method (as opposed to the argument of an array-like object).

If you do not want to collect all of the remaining parameters, you can combine the regular parameters with the remaining parameters.

function multiplyAndSumArgs(multiplier, ... numbers) { console.log(multiplier); // 2 console.log(numbers); // [5, 6] const sumArgs = numbers.reduce((sum, number) => sum + number); return multiplier * sumArgs; } multiplyAndSumArgs(2, 5, 6); / / = > 22Copy the code

Multiplier is a general parameter that takes the value of the first parameter. And then the remaining arguments… Numbers receives the remaining parameters.

The differences between the remaining arguments and arguments objects

There are three main differences between the remaining arguments and arguments objects:

  • The remaining arguments contain only arguments that have no corresponding parameters, whereas the Arguments object contains all arguments passed to the function.

  • The Arguments object is not a real Array and the remaining arguments are real Array instances, meaning you can use all the Array methods directly on it, such as sort, Map, forEach, or POP.

  • The Arguments object also has additional properties (such as the Callee property).

6. Summary

In addition to basic usage, JS provides many useful features when handling function arguments.

When parameters are missing, you can easily set defaults.

All the functionality of JS deconstruction can be applied to parameters. You can even combine deconstruction with default parameters.

Arguments is a special array-like object that contains all the arguments used in a function call.

As a better alternative to arguments, you can use the residual argument feature. It also holds a list of parameters, however, it stores them in an array.


The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: dmitripavlutin.com/javascript-…

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.