Alex
Alex

Reputation: 2649

call function on javascript array only if it exists, return empty array otherwise

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);

Upvotes: 2

Views: 168

Answers (1)

Alexander Gorelik
Alexander Gorelik

Reputation: 4385

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

Basically the same as Tushar but without unnecessary sort.

Upvotes: 1

Related Questions