I see responses saying why not arr.last.
I think they are completely missing the point.
True the article used -1 as the example value to get the last element, but the point of .at() is that negative indices start at the end, so -2 is the next to last element and -3 the one before that one, etc.
I'd assume that an index of -n of an n element array would be the first element and any index less than -n is undefined.
In addition .at() lets you use the index value stored in a variable, whereas .last does not.
Well then... What is? The only benefits over indices seem to be that it throws on non-array and that you can use valid negative indices.
For negative indices, the main purpose is most definitely .at(-1), since anything dynamic still requires knowing the .length, and anything less than -1 implies a data structure that should probably be an object in the first place.
And if I want to throw on non-array, I'll just use TypeScript.
I see responses saying why not arr.last.
I think they are completely missing the point.
True the article used -1 as the example value to get the last element, but the point of .at() is that negative indices start at the end, so -2 is the next to last element and -3 the one before that one, etc.
I'd assume that an index of -n of an n element array would be the first element and any index less than -n is undefined.
In addition .at() lets you use the index value stored in a variable, whereas .last does not.
Honestly, I don't think getting the last is the real reason for "at"
Well then... What is? The only benefits over indices seem to be that it throws on non-array and that you can use valid negative indices.
For negative indices, the main purpose is most definitely
.at(-1)
, since anything dynamic still requires knowing the.length
, and anything less than-1
implies a data structure that should probably be an object in the first place.And if I want to throw on non-array, I'll just use TypeScript.
Throws on non-array seems to me a real reason for using "at". TypeScript is not everywhere yet and even it is, there's still "any".
You would implement a stack as an object? Trippy ...