Insert array elements conditionally


We can conditionally insert elements in an Array, there's one way to do that:

const flag1 = true
const flag2 = false

const arr = [ 
  ...(flag1 ? ['element'] : []),

flag1 values will be present in this Arrat, while flag2 not.

Please note

In case of objects, we could use a short-circuit technic, like "condition && { obj: 1 }"", but in case of arrays it won't work, so we need to use a ternary operator to output an empty array, if condition won't be true.

I also wrote an article regards objects.