Optional parameter in Arrow Function
Asked Answered
M

2

10

I have a handler like

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

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

Maduro answered 18/8, 2018 at 23:3 Comment(1)
You can use a default value : (k0, k1 = true, v) the problem is that if you want to have the v param, you'll need to explicitely pass undefined as a second paramDigestive
E
11

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 }) => {
  ...
};
Everybody answered 18/8, 2018 at 23:14 Comment(0)
M
0

You can now do this with default assignment like you'd expect:

handleSelect = (k0, k1 = null, v = null) => {

The docs are pretty vague on this, for some reason, but I've verified this is working in the major browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

Mother answered 15/3 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.