Lodash _.last() method
What you’ll learn
- How
_.last(array)reads the final element without mutating the collection. - That an empty array yields
undefined, and how array-likelengthpicks the last index. - How this compares to
array[array.length - 1], optional chaining, andat(-1). - Try each example in the editor (
?tryit=1,2,3) with Lodash from a CDN.
Overview
_.last is the Lodash name for “give me the final value.” It resolves the last occupied index, returns undefined when there is no tail element, and never allocates a new collection. It pairs conceptually with _.head() at the front of the list.
Tail read
One call returns the element reference at the end of a dense array or array-like object.
Empty-safe
Empty input yields undefined, not an exception—same spirit as _.head.
Importable
Use lodash/last next to other focused Lodash utilities in a tree-shaken bundle.
Syntax
_.last(array) - array: collection to inspect (array-like values are coerced).
- Returns: the element at the last index, or
undefinedwhen the collection is empty or has no occupied last slot.
Non-empty array
The last element is returned by reference; mutating it still affects the original array slot.
import last from "lodash/last";
last(["alpha", "beta", "gamma"]);
// "gamma" Empty array
There is no last index when length is 0, so Lodash returns undefined. Combine with nullish coalescing when you need a default.
import last from "lodash/last";
last([]);
// undefined
last([]) ?? "fallback";
// "fallback" Array-like object
Numeric keys plus length behave like an array; the last slot is index length - 1.
import last from "lodash/last";
last({ 0: "north", 1: "east", length: 2 });
// "east" 📋 _.last vs [length - 1] vs at(-1)
| API | Strength | Note |
|---|---|---|
_.last(array) | Named intent, array-like support | Matches other Lodash imports in a utility module |
array[array.length - 1] | Zero overhead native syntax | Guard length when the array might be empty |
array.at(-1) | Relative indexing from the end | ES2022; reads the same final element on dense arrays |
Pitfalls to avoid
Hole at the last index
A sparse array may have length > 0 while the final slot is empty; last can still yield undefined even though the array is not logically “empty.”
Falsy last elements
0, "", and false are valid tail values; do not treat them as missing when branching.
Not pop
last does not remove the element. Use pop, slice(0, -1), or _.initial() when you need a shorter array.
❓ FAQ
Summary
- Purpose:
_.last(array)returns the final element orundefinedwhen there is none. - Array-like: the last index is derived from
lengthminus one. - Next: Lodash _.lastIndexOf(), _.join() (earlier in this track), or the array methods hub.
Use _.initial() when you need every element except the last; _.last only reads the final slot.
6 people found this page helpful
