apps-script-utils 2.1.1 Help

last

function last<T>(array: T[]): T | undefined; function last<T>(array: T[], n: number): T[]; function last<T>(array: T[], n?: number): T | T[] | undefined;

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

array

T[]

The array to read from. Left untouched.

n (optional)

number

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

TypeError

array is not an array.

TypeError

n is given and is not an integer.

Examples

One element, or several

last([1, 2, 3]); // => 3 last([]); // => undefined last([1, 2, 3], 2); // => [2, 3] — order preserved

Reading the most recent entries of a log sheet

/** * Logs the ten newest entries of a log sheet, oldest of the ten first. */ export function logRecentEntries(sheet: GoogleAppsScript.Spreadsheet.Sheet): void { const rows = sheet.getDataRange().getValues().slice(1); for (const row of last(rows, 10)) { Logger.log(row.join(" | ")); } }
function logRecentEntries(sheet) { const rows = sheet.getDataRange().getValues().slice(1); for (const row of last(rows, 10)) { Logger.log(row.join(" | ")); } }

Clamping

last([1, 2], 10); // => [1, 2] last([1, 2], -1); // => [] last([1, 2], 1.5); // throws TypeError: Input 'n' must be an integer.

See also

Source

src/lang/array/last.ts

23 September 2026

This documentation was generated with AI (Claude) from the library's source code.