Aller au contenu principal

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