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
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
You could spread an (empty) array.
console.log([...(0 ? [{ name : "example" }] : [])]);
console.log([...(1 ? [{ name : "example" }] : [])]);
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);
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']