Skip to main content

last()

last<T>(array): T | undefined

Gets the last element of array.

DEPRECATED

Use array[array.length - 1] or array.at(-1) directly instead.

Reason:
Native equivalent method now available


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: T[]โ€‹

The array to query.


Returns: T | undefinedโ€‹

The last element of the array, or undefined if empty.


See Alsoโ€‹


Sinceโ€‹

2.0.0


Also known asโ€‹

last (Lodash, es-toolkit, Remeda, Radashi, Ramda, Effect, Antfu) ยท โŒ (Modern Dash)


Exampleโ€‹

const numbers = [1, 2, 3, 4, 5];

// โŒ Deprecated approach
const lastElement = last(numbers);
console.log(lastElement); // 5

// โœ… Recommended approach
const lastNative = numbers[numbers.length - 1];
console.log(lastNative); // 5

// โœ… Modern approach with ES2022
const lastModern = numbers.at(-1);
console.log(lastModern); // 5

How it works?โ€‹

Gets the last element of an array. Deprecated: Use array[array.length - 1] or array.at(-1) directly.

Native Equivalentโ€‹

// โŒ last(arr)
// โœ… arr[arr.length - 1]
// โœ… arr.at(-1) // ES2022

Use Casesโ€‹

Get last element ๐Ÿ“Œโ€‹

Retrieve the last element of an array.

const items = [1, 2, 3, 4, 5];
items.at(-1);
// => 5

Get most recent itemโ€‹

Get the most recent entry from a history.

const history = ["page1", "page2", "page3"];
history.at(-1);
// => "page3"

Access final resultโ€‹

Get the last item from a processed array.

const results = computeAll();
results.at(-1);
// => final result