Timeline for answer to Get the last item in an array by kritzikratzi
Current License: CC BY-SA 4.0
Post Revisions
12 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Feb 18, 2025 at 11:44 | history | edited | Taimoor Changaiz | CC BY-SA 4.0 |
added 319 characters in body
|
| Jun 22, 2020 at 20:14 | comment | added | kritzikratzi |
@Govan please see my comment. you can call this an exorbitant number of times per second. if you need more, or have the array length readily available, use normal array access for maximum performance arr[arr.length-1]
|
|
| Jun 21, 2020 at 22:30 | comment | added | Govan | this method is very slow | |
| Jun 2, 2020 at 18:54 | comment | added | kritzikratzi | @mvmn i did a benchmark a long time ago, throughput was around one or two million calls per second on a single 2.4ghz thread. so unless you have solve problems you shouldn't solve in JS anyways, it won't be noticable (iirc slowdown compared to arr[arr.length-1] was 50-100x) | |
| Jun 1, 2020 at 17:32 | comment | added | mvmn | But you should avoid creating new arrays unless this code is not called often. Otherwise it will put an extra strain on garbage collection, and/or will make browser use more memory. | |
| May 7, 2020 at 18:21 | comment | added | kritzikratzi | @Badrush slice() makes new array with a copy of a single element, and pop modifies only that copy. the original array remains unharmed | |
| Mar 11, 2019 at 6:30 | comment | added | diachedelic |
using destructuring is nice too: const [lastItem] = arr.slice(-1)
|
|
| S May 16, 2014 at 21:32 | history | suggested | kuporific | CC BY-SA 3.0 |
No reason why the "or" needed to be code formatted, reads better when not.
|
| May 16, 2014 at 21:30 | review | Suggested edits | |||
| S May 16, 2014 at 21:32 | |||||
| Oct 10, 2013 at 23:37 | history | edited | kritzikratzi | CC BY-SA 3.0 |
explained case when there's no element in the array
|
| Jul 20, 2013 at 0:25 | history | edited | kritzikratzi | CC BY-SA 3.0 |
added suggestion by @skizeey
|
| Aug 23, 2012 at 20:19 | history | answered | kritzikratzi | CC BY-SA 3.0 |