1

Primarily an es6/7 question dealing with object destructuring.

Suppose I have this sample function:

const sample = (var1, var2) => {
  const obj = {
   one: var1
  };

  if (var2) {
    obj.two = var2;
  }

  return obj;
};

Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too".

Is there a more elegant way to achieve the same effect but with object destructuring?

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • The closest I can think of is: `const sample = (one, two) => ({one, two});` That would still define the `two` property, but the value would be `undefined`. – 4castle Apr 16 '17 at 22:51
  • Yeah I ran into that too. For a lot of cases it would work but sometimes just the existence of the property can be a problem. – Geuis Apr 16 '17 at 22:55
  • 1
    then I'd write it as `const sample = (one, two) => two? {one, two}: {one};` – Thomas Apr 16 '17 at 23:02
  • @Thomas I think that's it. Why don't you add that comment as an answer so I can accept it? Thanks! – Geuis Apr 16 '17 at 23:09
  • It would be possible if you would like `two` to fall back to some default value, like it is shown here http://stackoverflow.com/a/43431245/3731501 . Otherwise, no, you need `if (var2 !== undefined) ...` ( `if (var2)` won't work). – Estus Flask Apr 16 '17 at 23:10

1 Answers1

3

You can also write your function as

const sample = (one, two) => two? {one, two}: {one};

Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too"

As with your code, be careful with the values you add as a second argument. There are way more falsy values than just undefined, some of which you may want to assign to the result. If the criteria is whether the second argument is defined, I'd explicitly check against undefined:

const sample = (one, two) => two !== undefined? {one, two}: {one};
4castle
  • 32,613
  • 11
  • 69
  • 106
Thomas
  • 11,958
  • 1
  • 14
  • 23