2

is there a way to return nothing for ternary operator I mean

const a = [ 0 ? { name : "example" } : null ]

when i print a = [null]

or:

const a = [ 0 && {name:"example"}]

a will be [false]

i expected that a = [] for case 1

3 Answers3

5

You could spread an (empty) array.

console.log([...(0 ? [{ name : "example" }] : [])]);
console.log([...(1 ? [{ name : "example" }] : [])]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
4

No. It isn't possible. You are going to get a value back.

If you conditionally want a value, then either make the decision outside the array or filter the null values out afterwards.

e.g.

const a = 0 ? [ { name: "example" } ] : [];

or

const a = [ 0 ? { name : "example" } : null ].filter(Boolean);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

null is a perfectly valid array value in Javascript, as is undefined.

You can simply construct the array on demand...

const a = 0 ? [{ name : "example" }] : [];

or if this is part of a larger array construction, use splats...

const a = [
    'a',
    ...(0 ? [{name : "example"}] : []),
    'b'
];

console.log(a); //-> ['a', 'b']
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145