Reputation: 17333
I have a section of code like the following:
var arr = [];
// bit further down in the code
arr[arr.length - 1].id + 1
Evidently, if arr
is empty, then arr[arr.length - 1]
would return me undefined
.
Now I know that I can cast that to 0
with a simple or statement like so:
arr[arr.length - 1] || 0; // will return 0 if arr[arr.length - 1] is undefined
However, I wish to either return arr[arr.length - 1].id
, or 0
, if arr[arr.length - 1]
is undefined.
Is there a shorthand notation that I can use to solve this issue? I have tried:
arr[arr.length - 1].id || 0
However, this returns me an error Cannot read property 'id' of undefined
, which undoubtedly would make sense in this context.
Upvotes: 0
Views: 49
Reputation: 9852
That's because it's looking for .id
, which doesn't exist because the engine is looking for a property of a unknown object. You must first check is arr
is defined, then proceed the operation:
var arr = [];
// It will check for ID only if arr exists and output the result.
// Otherwise value is 0
(arr && arr[arr.length - 1].id) || 0
Upvotes: 0
Reputation: 413702
You can check the length first:
arr.length && (arr[arr.length - 1].id + 1) || 0;
That will evaluate to the last element's "id" value plus 1, or else zero if the array is empty.
Upvotes: 2