Master JavaScript’s Array.at(): Simplify Access to Elements from Both Ends
This article explains how JavaScript arrays are zero‑based, demonstrates traditional bracket indexing, introduces the new Array.prototype.at() method for both positive and negative indices, and shows concise code examples that make accessing the first, middle, and last elements easier and more readable.
JavaScript arrays are zero‑based, meaning the first element has index 0 and the last element’s index equals the array’s length minus 1.
Typically we access elements with bracket notation array[index]; if the index is invalid, JavaScript returns undefined rather than throwing an error.
const array = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr[0]); // logs 'this is the first element'
console.log(arr[1]); // logs 'this is the second element'Bracket syntax works well for forward indexing, but sometimes we want to access elements from the end, such as the last element.
const array = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr[arr.length - 1]); // logs 'this is the last element'ECMAScript introduced a new method Array.prototype.at() that accepts an integer and returns the item at that index, supporting both positive and negative numbers. Negative integers count backward from the end of the array.
const array1 = ['this is the first element', 'this is the second element', 'this is the last element'];
console.log(arr.at(0)); // logs 'this is the first element'
console.log(arr.at(-2)); // logs 'this is the second element'
console.log(arr.at(-1)); // logs 'this is the last element'The examples highlight the simplicity and readability of the at() method.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
