JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
What is the Array.prototype.at() method and why is it useful?
junior LevelMost AskedCode ExampleFormsPerformancePrototypes
The at() method (introduced in ES2022) allows you to access array elements using both positive and negative indices. It provides a simpler and more intuitive way to access elements from the end of an array.
Syntax:
javascript
array.at(index)
Key Features:
- Negative Indexing: Negative indices count from the end of the array
- Cleaner Syntax: More readable than traditional methods for accessing end elements
- Works on Strings: Also available on String.prototype
- Returns undefined: Returns
undefinedfor out-of-bounds indices (like bracket notation)
Examples:
javascript
const fruits = ['apple', 'banana', 'orange', 'mango', 'grape'];
// Positive indices (same as bracket notation)
console.log(fruits.at(0)); // 'apple'
console.log(fruits.at(2)); // 'orange'
console.log(fruits[2]); // 'orange' (equivalent)
// Negative indices (the game changer!)
console.log(fruits.at(-1)); // 'grape' (last element)
console.log(fruits.at(-2)); // 'mango' (second to last)
console.log(fruits.at(-5)); // 'apple' (first element)
// Out of bounds
console.log(fruits.at(10)); // undefined
console.log(fruits.at(-10)); // undefined
// Comparison with traditional approaches:
const arr = [10, 20, 30, 40, 50];
// Getting last element
console.log(arr.at(-1)); // 50 ✅ Clean and simple
console.log(arr[arr.length - 1]); // 50 ❌ Verbose
console.log(arr.slice(-1)[0]); // 50 ❌ Creates new array
// Getting second to last
console.log(arr.at(-2)); // 40 ✅ Clean
console.log(arr[arr.length - 2]); // 40 ❌ Verbose
// Dynamic index from the end
const n = 3;
console.log(arr.at(-n)); // 30 ✅ Clean
console.log(arr[arr.length - n]); // 30 ❌ Verbose
Works with Strings:
javascript
const text = 'Hello, World!';
console.log(text.at(0)); // 'H'
console.log(text.at(-1)); // '!'
console.log(text.at(-6)); // 'W'
Real-World Use Cases:
javascript
// 1. Processing the last few elements
const scores = [85, 92, 78, 95, 88];
const lastScore = scores.at(-1);
const secondLastScore = scores.at(-2);
console.log(`Last two scores: ${secondLastScore}, ${lastScore}`);
// 2. Circular/wraparound logic
function getElement(array, index) {
// Positive: use directly
// Negative: count from end
return array.at(index);
}
// 3. Working with dynamic data
const messages = ['msg1', 'msg2', 'msg3', 'msg4'];
const latest = messages.at(-1); // Always gets the latest
// 4. Palindrome checking
function isPalindrome(str) {
const len = str.length;
for (let i = 0; i < len / 2; i++) {
if (str.at(i) !== str.at(-i - 1)) {
return false;
}
}
return true;
}
console.log(isPalindrome('racecar')); // true
// 5. Safe access with method chaining
const data = [1, 2, 3];
console.log(data.filter(x => x > 1).at(-1)); // 3 (last of filtered results)
Benefits over Traditional Methods:
javascript
const items = ['a', 'b', 'c', 'd', 'e'];
// Traditional (verbose and error-prone)
const last = items[items.length - 1];
const thirdFromEnd = items[items.length - 3];
// Modern (clean and intuitive)
const last2 = items.at(-1);
const thirdFromEnd2 = items.at(-3);
// Especially useful in expressions
const result = someFunction() || items.at(-1); // Clean
const result2 = someFunction() || items[items.length - 1]; // Cluttered