at()
at<
T>(arr,index):T|undefined
Returns the item at the given index, allowing for positive and negative integers.
Negative integers count back from the last item in the array.
Use array.at(index) directly instead.
Reason:
Native equivalent method now available
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
arr: T[]โ
The array to query.
index: numberโ
The index of the element to return.
Returns: T | undefinedโ
The element at the given index, or undefined if out of bounds.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
at (Lodash, es-toolkit, Antfu) ยท get (Effect) ยท nth (Ramda) ยท โ (Remeda, Radashi, Modern Dash)
Exampleโ
const numbers = [1, 2, 3, 4, 5];
// โ Deprecated approach
const first = at(numbers, 0);
console.log(first); // 1
const last = at(numbers, -1);
console.log(last); // 5
// โ
Recommended approach
const firstNative = numbers[0];
console.log(firstNative); // 1
const lastNative = numbers[numbers.length - 1];
console.log(lastNative); // 5
// โ
Modern approach with ES2022
const firstModern = numbers.at(0);
console.log(firstModern); // 1
const lastModern = numbers.at(-1);
console.log(lastModern); // 5
How it works?โ
Returns the item at the given index, supporting negative indices.
Deprecated: Use array.at(index) directly (ES2022).
Negative Indexโ
Native Equivalentโ
// โ at(arr, -1)
// โ
arr.at(-1)
Use Casesโ
Access array elements with negative indices ๐โ
Retrieve elements from the end of an array using negative indices.
const history = ["page1", "page2", "page3", "page4", "page5"];
history.at(-1); // => "page5"
history.at(-2); // => "page4"
Access step in multi-step wizardโ
Get the current step data based on a dynamic step index.
const wizardSteps = [{ id: "personal" }, { id: "address" }, { id: "payment" }];
wizardSteps[currentStepIndex];
// => { id: "payment" }
Access carousel slide at offsetโ
Get slides relative to current position for navigation.
const slides = ["intro", "features", "pricing", "contact"];
slides[currentIndex + 1]; // next
slides[currentIndex - 1]; // prev