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