Q:

How to add an element to an array only if a condition is fulfilled

There is an arrow function creating an array like:
const myFunction = () => ["a", "b", "c"];

I want to add an argument to it that must add another element if the argument is true.
Like here:
const myFunction = (arg) => ["a", "b", "c", arg ? "d" : null];

the problem with this solution is that is still adds a null element if arg !== true but I want to don't add anything in this case.

A:

You can use array spread. According to the value of arg an empty array or an array that contains d will be spreaded into the result array:

const myFunction = (arg) => ["a", "b", "c", ...arg ? ['d'] : []];

console.log(JSON.stringify(myFunction(true))); // ["a","b","c","d"]

console.log(JSON.stringify(myFunction())); // ["a","b","c"]

