First of all, we know that there is no function overloading in JS, so we need to use a few tricks when dealing with variable function arguments.

arguments

Arguments is an internal variable that exists in functions (except arrow functions). Arguments contains information about the arguments passed to the function. Arguments [0] calls the first argument to a function, arguments[1] calls the second function, and so on. Even so, Arguments is not an array object, it just has access to indexes and length attributes. We can convert arguments to a real array:

var args = Array.prototype.slice.call(arguments);
var args = [].slice.call(arguments);
var args = Array.from(arguments);
var args = [...arguments];
Copy the code

Arguments has engine optimization issues and we will not use arguments objects in the following tips and use ES6 syntax instead.

Uncertain parameters

Define function func([params][,…args]). This function can accept arguments of variable length.

function func(. args) {
  // Destruct the assignment
  console.log(`arguments: ${args}`); // args is array
  let [params1, params2, ...paramsRest] = args; // Get the array paramsRest that is passed in the first parameter params1, the second parameter params2, and the remaining parameters
}
Copy the code

Now let’s implement a function that calls another function internally.

const foo = (params1, params2, params3) = > {
  return params1 + params2 + params3;
};

// We don't need to know the parameter list for foo. Use deconstruction to manipulate arbitrary parameter lists.
const func = (. args) = >{ foo(... args);// expand when the function is called
  foo.call(null. args);// Change the value of this with call.
  foo.apply(null, args); // Apply accepts an array of parameters directly
};
Copy the code

Similarly, some parameters are determined and some parameters are variable:

function func(params1, ... args) {
  console.log(`arguments: ${args}`); // An array of remaining parameters
}
Copy the code

Callback is the last parameter in Node.js. If the intermediate parameter is variable, use typeof to check:

// Determine the parameters
function func(err, params1, params2, callback) {
  if (typeof params1 === 'function') {
    callback = params1;
    params1 = null;
    params2 = null;
  } else if (typeof params2 === 'function') {
    callback = params2;
    params1 = null;
  } else if (typeofcallback ! = ='function') {
    throw new Error('Parameter error'); }}// Some tricks
function func(err, ... args) {
  // The callback function is the last item in the array args
  const callback = typeof args[args.length - 1= = ='function' ? args.pop() : null;
  const [params1 = null, params2 = null] = args;
}
Copy the code

In native JS, some functions can take either a list of arguments or an array of arguments, such as concat. We can also use this concat feature to write functions like this:

const func = (. args) = > {
  constparams = [].concat(... args);// Take advantage of concat's ability to accept multiple arguments or a single array simultaneously
  console.log(params);
};
Copy the code

The default parameters

Basic grammar

function func(a, b = 0) {
  return a + b;
}
func(5); // b Defaults to 0
Copy the code

Deconstruct and expand with objects

function func(a, { opt1 = '1', opt2 = '2' }) {
  console.log(a, opt1, opt2);
}
func(0, { opt1: '4' }); / / 0 "4", "2"
func(0); / / error! Because the second argument is undefined

function func1(a, { opt1 = '1', opt2 = '2' } = {}) {
  console.log(a, opt1, opt2);
}
func1(0); 0 "1" "2"
Copy the code

It can also be handled inside a function

function func(a, opts) {
  opts = Object.assign(
    {
      opt1: '1',
    },
    opts
  ); // Assign the default value using object. assign

  opts = {
    opt1: '1'. opts, };// Similar to object.assign

  const { opts1 = '1', opts2 = '2' } = opts; // Destruct the assignment and give the default value.
}
Copy the code

Error handling

With the syntax of default parameters, we can implement some error detection, such as requiring that the parameter must be passed:

function mandatory() {
  throw new Error('Missing parameter');
}
function foo(mustBeProvided = mandatory()) {
  return mustBeProvided;
}

foo(); // Error: Missing parameter
Copy the code

Check the maximum length of the parameter

function func(x, y, ... extra) {
  if (extra.length > 0) {
    throw new Error();
  }
}
Copy the code