0
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?

6
  • 1
    Do you mean the optional chaining operator? Based on the semantics documented there, I wouldn't expect this to do anything other than pass undefined to .concat as its second argument, right? Commented Jan 6, 2021 at 22:38
  • 1
    Your second version is easier to read than the hypothetical version, anyway; going further I'd actually suggest an if/else statement pair. Make your code easy to read first. Commented Jan 6, 2021 at 22:40
  • 2
    you could also do acts.change.concat(addendum?.changedActions??"")) Commented Jan 6, 2021 at 22:41
  • const acts.change is invalid syntax. Commented Jan 6, 2021 at 22:42
  • 2
    @emrhzc Shouldn't it be ??[]? Commented Jan 6, 2021 at 22:44

2 Answers 2

0

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??[]])
Sign up to request clarification or add additional context in comments.

Comments

-2

Thanks, friends, testing revealed that

acts.change.concat(addendum?.changedActions??[]))

is the behavior I was looking for.

1 Comment

The more readable (and backwards compatible and performant) form would be if(addendum) acts.change.concat(addendum.changedActions);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.