Lodash _.takeRight() method
What you’ll learn
- How
_.takeRight(array, n)clones the trailing suffix without mutating the source. - That omitting
nkeeps exactly one tail element andn = 0yields[]. - When negative _.slice() offsets or predicate helpers express the intent clearer.
- Try each example in the editor (
?tryit=1,2,3) with Lodash from a CDN.
Prerequisites
Read _.take() first—the APIs differ only in which end they measure from.
- You understand shallow copies: nested values inside the suffix remain aliased.
- You can open Try-it labs or run snippets locally.
Overview
_.takeRight captures trailing crumbs—recent audit entries, final pagination page, or suffix tokens—without recomputing lengths manually.
Suffix-only
Anchors at the highest indexes—ideal complements to leading-edge helpers.
Count clamping
Oversized counts snap to the full span instead of throwing.
Non-destructive
Earlier cells remain available for alternate projections.
Syntax
_.takeRight(array, [n=1]) - array: dense collection or array-like value.
- n: how many trailing elements to include (defaults to
1). - Returns: new array with at most
nslots copied from the end.
Grab the closing run
Order inside the suffix mirrors the original sequence ending at the last index.
import takeRight from "lodash/takeRight";
takeRight(["spring", "summer", "autumn", "winter"], 2);
// → ["autumn", "winter"] Zero count vs default
n = 0 produces []; omitting n captures only the final element.
import takeRight from "lodash/takeRight";
takeRight(["east", "south", "west"], 0);
// → []
takeRight(["east", "south", "west"]);
// → ["west"] Count larger than length
Huge counts normalize to a whole-array shallow duplicate.
import takeRight from "lodash/takeRight";
takeRight([7, 8, 9], 100);
// → [7, 8, 9] 📋 _.takeRight vs _.take, _.slice, _.dropRight
| API | Edge | Use case |
|---|---|---|
_.takeRight(array, n) | Trailing | Known suffix widths such as recent windows |
_.take(array, n) | Leading | Prefixes instead of suffixes |
_.slice(array, -n) | Trailing via negative start | Native-style slicing when Lodash import unnecessary |
_.dropRight(array, n) | Removes trailing cells | Keep the complementary head segment |
Pitfalls to avoid
Shallow suffix
Nested structures remain referenced—clone deeply only when required.
initial confusion
_.initial() drops exactly one tail slot but returns the complementary prefix; takeRight(_, 1) keeps only the last element.
Sparse arrays
Holes may appear depending on engines—prefer dense arrays for deterministic QA.
❓ FAQ
Summary
- Purpose:
_.takeRight(array, n)shallow-copies up tontrailing elements (defaultn = 1). - Pairs with: _.dropRight() for mirrored trims and _.take() for the opposite edge.
- Next: Lodash _.takeRightWhile(), _.take() (previous), or the array methods hub.
_.takeRight pairs naturally with _.dropRight() the same way _.take() pairs with _.drop()—mirror trims from opposite ends of the buffer.
6 people found this page helpful
