Search code examples
javascriptconditional-operator

Ternary operator return nothing


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


Solution

  • You could spread an (empty) array.

    console.log([...(0 ? [{ name : "example" }] : [])]);
    console.log([...(1 ? [{ name : "example" }] : [])]);