last
This is what array[array.length - 1] is written for — an expression that yields undefined on an empty array while looking like it meant something else. last says it plainly and returns undefined in the same case.
The n form takes from the end but preserves the original order: last([1, 2, 3], 2) is [2, 3], not [3, 2]. n is clamped, so a negative count yields an empty array and a count beyond the length yields the whole array. The input is not modified.
Parameters
Parameter | Type | Description |
|---|---|---|
|
| The array to read from. Left untouched. |
|
| How many elements to take. An integer; omit it to take a single one. |
Returns
T | T[] | undefined — T | undefined when n is omitted — the last element, or undefined for an empty array. T[] when n is given — a new array of at most n elements, in their original order.
Throws
Exception | Condition |
|---|---|
|
|
|
|
Examples
One element, or several
Reading the most recent entries of a log sheet
Clamping
See also
first— the same two forms, taken from the start.
Source
This documentation was generated with AI (Claude) from the library's source code.