2

I'm getting the Expression expected error when I try this:

const func = () => [0, 1]
const possibly_undefined_var = { var: 3 }

const var = [possibly_undefined_var?.var ?? ...func()]

Expected result: [3] or [0, 1]

I was wondering if there is any way to use the array spread operator along with nullish coalescing in this example.

Klobox
  • 33
  • 3

1 Answers1

4

I think the clearest way to do this would be to use the conditional operator:

const obj = possibly_undefined_var?.var;
const arr = obj ? [obj] : [...func()];

I can't think of any good way to alternate obj with a spread of func inside a single array literal that isn't unnecessarily confusing and verbose (and would require the conditional operator anyway, I think).

If obj can be falsey without being null or undefined, then it takes a bit more code:

const obj = possibly_undefined_var?.var;
const arr = (obj === null || obj === undefined) ? [...func()] : [obj];
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • `obj == null` handles both `null` and `undefined`. – Unmitigated May 10 '21 at 03:24
  • 1
    Yes, you can do that too, but I prefer to avoid `==` in all cases, `===` has many fewer gotchas. https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons – CertainPerformance May 10 '21 at 03:26