MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/learnjavascript/comments/qg23w3/negative_array_indexing_using_at_method/hi82eqo/?context=3
r/learnjavascript • u/jd_300 • Oct 26 '21
69 comments sorted by
View all comments
Show parent comments
11
const lastElement = arr[arr.length - 1]
Why wouldn't you just do the above?
17 u/ExclusiveOar Oct 26 '21 Preference. arr[-1] is allowed in other languages and it's a nice to have.arr.at(-1) is arguable cleaner than arr[arr.length - 1]. Personally I wouldn't bother until JS eventually supports arr[-1]. 1 u/[deleted] Oct 27 '21 arr.at(-1) is also constant time right? 1 u/ExclusiveOar Oct 27 '21 No expert here, but I would assume so.But so is arr[arr.length - 1] because array.length isn't calculated here, its a prop already on the array.You can see this by creating an array, console.log it and expand it in the console.
17
Preference. arr[-1] is allowed in other languages and it's a nice to have.
arr.at(-1) is arguable cleaner than arr[arr.length - 1]. Personally I wouldn't bother until JS eventually supports arr[-1].
1 u/[deleted] Oct 27 '21 arr.at(-1) is also constant time right? 1 u/ExclusiveOar Oct 27 '21 No expert here, but I would assume so.But so is arr[arr.length - 1] because array.length isn't calculated here, its a prop already on the array.You can see this by creating an array, console.log it and expand it in the console.
1
arr.at(-1) is also constant time right?
1 u/ExclusiveOar Oct 27 '21 No expert here, but I would assume so.But so is arr[arr.length - 1] because array.length isn't calculated here, its a prop already on the array.You can see this by creating an array, console.log it and expand it in the console.
No expert here, but I would assume so.
But so is arr[arr.length - 1] because array.length isn't calculated here, its a prop already on the array.
You can see this by creating an array, console.log it and expand it in the console.
11
u/Gibbo3771 Oct 26 '21
Why wouldn't you just do the above?