Insert array elements conditionally

Published 
JavaScript

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

const flag1 = true
const flag2 = false

const arr = [ 
  element1,
  element2,
  ...(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.