ES6 Array spread operator with nullish coalescing

Viewed 710

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.

1 Answers

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];
Related