The [at()] method is a new way to get an element from an array or string by index. Main difference from direct indexing [arr[index]] — [at()] supports negative indices! 🔄
const arr = ['a', 'b', 'c'];
// Direct index
console.log(arr[0]); // 'a'
console.log(arr[-1]); // undefined ❌
// at method
console.log(arr.at(0)); // 'a'
console.log(arr.at(-1)); // 'c' ✅ (last element)The [at()] method is like an improved version of regular element access. It allows getting elements from the end without counting length! 🎯
Regular way — specify slot number directly:
const fruits = ['apple', 'banana', 'orange'];
// Direct index
console.log(fruits[0]); // 'apple' (first)
console.log(fruits[2]); // 'orange' (third)
// Negative indices don't work
console.log(fruits[-1]); // undefined ❌
console.log(fruits[-2]); // undefined ❌[at()] understands negative numbers — counts from the end:
const fruits = ['apple', 'banana', 'orange'];
// Positive indices — as usual
console.log(fruits.at(0)); // 'apple' (first)
console.log(fruits.at(2)); // 'orange' (third)
// Negative — from the end!
console.log(fruits.at(-1)); // 'orange' (last) ✅
console.log(fruits.at(-2)); // 'banana' (second to last) ✅Negative indices in [at()] — like counting from the end:
const arr = ['a', 'b', 'c', 'd'];
// -1 — last element
console.log(arr.at(-1)); // 'd'
// -2 — second to last
console.log(arr.at(-2)); // 'c'
// -3 — third from end
console.log(arr.at(-3)); // 'b'
// Formula: arr.at(-n) = arr[arr.length - n]// ✅ Convenient for last elements
const scores = [85, 92, 78, 96];
// Instead of this:
console.log(scores[scores.length - 1]); // 96
// Can do this:
console.log(scores.at(-1)); // 96 ✅// ✅ Convenient with variables
const arr = [1, 2, 3, 4, 5];
const index = -2; // Negative index
console.log(arr.at(index)); // 4 (second from end)const arr = ['a', 'b', 'c'];
// ❌ Mistake — think negative works
console.log(arr[-1]); // undefined
// ✅ Correct — use at()
console.log(arr.at(-1)); // 'c'const arr = ['a', 'b', 'c'];
// ❌ Not using at() advantages
console.log(arr.at(0)); // 'a' — could just use arr[0]
// ✅ Using as intended
console.log(arr.at(-1)); // 'c' — only through at()Understanding the [at()] method helps work more conveniently with elements from the end of arrays! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪