Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in Arrow Function

I have a handler like

handleSelect = (k0, k1, v) => {
    ...
    }
};

And I want to make k1 here optional. Is there a good way?

like image 997
Mr.cysl Avatar asked Aug 18 '18 23:08

Mr.cysl


People also ask

How do you pass parameters in arrow function?

The arrow function can be shortened: when it has one parameter you can omit the parentheses param => { ... } , and when it has one statement you can omit the curly braces param => statement . this and arguments inside of an arrow function are resolved lexically, meaning that they're taken from the outer function scope.

What is optional parameter?

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.

How can we make a parameter of a function optional?

Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.

Can arrow functions have parameters?

Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.


1 Answers

There is no good way. This isn't specific to React or arrows.

A variadic function with optional parameter in the middle requires to parse arguments:

handleSelect = (...args) => {
  let k0, k1, v;
  if (args.length > 2) {
    [k0, k1, v0] = args;
  } else {
    [k0, v0] = args;
    k1 = 'default';
  }
  ...
};

This may result in obscure API. A better recipe for a function with several parameters some of which can be optional is to accept an object with options. A function doesn't depend on parameter order this way:

handleSelect = ({ k0, k1 = 'default', v }) => {
  ...
};
like image 148
Estus Flask Avatar answered Oct 17 '22 07:10

Estus Flask