2

what would be a good (concise) way in Javascript (ES6) to run a method (say, "sort") on an array only when the array exists, and return an empty array otherwise?

e.g. in this example "this.props.items" can be undefined and I don't want this to fail with "Cannot read property 'sort' of undefined":

const sortedItems = this.props.items.sort((a, b) => a.id - b.id);
1
  • 14
    (this.props.items || []).sort(... Commented Oct 27, 2016 at 3:44

1 Answer 1

1

const sortedItems = this.props.items ? this.props.items.sort() : []

Basically the same as Tushar but without unnecessary sort.

Sign up to request clarification or add additional context in comments.

1 Comment

Each unnecessary sort is likely to take less than one microsecond.

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.