javascriptnull-conditional-operator

Is there a null-conditional operator for array concatenation?


const addendum = null
const acts.change = [act1];
console.log( acts.change.concat(addendum?.changedActions) );

Outputs [act1, null] rather than the expected [act1]. Am I misusing the null-conditional operator or is

console.log( addendum ? acts.change.concat(addendum?.changedActions) : acts.change )

the best/briefest way to get what I'm looking for?


Solution

  • There's nothing built-in to make concat() ignore the argument. So you need to replace an undefined argument with an empty array in order to to concatenate nothing.

    You can use the null coalescing operator in additional to conditional chaining:

    addendum?.changedActions??[]
    

    To further reduce the syntax, use ES6 ellipsis instead of calling concat().

    console.log([...acts.change, ...addendum?.changedActions??[]])