Reputation: 2649
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
Reputation: 4385
const sortedItems = this.props.items ? this.props.items.sort() : []
Basically the same as Tushar but without unnecessary sort.
Upvotes: 1