DEV Community

Cover image for How This Simple Method Turned My Array Code from Messy to Neat
Gouranga Das Samrat
Gouranga Das Samrat

Posted on

How This Simple Method Turned My Array Code from Messy to Neat

How This Simple Method Turned My Array Code from Messy to Neat

Recently when I was going through an article when I stumbled on a cleaner way to grab array elements, and it’s changed how I code. It’s simple. It’s elegant.

Introduced in 2022, at() lets me grab array or string elements with intuitive indexing.

Array indexing the new way

Introduced in ECMAScript 2022, Array.prototype.at() simplifies indexing with a single method that handles both positive and negative indices.

Think of it as a shortcut that keeps your code concise and readable.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits.at(0)); // "apple"
console.log(fruits.at(-1)); // "cherry"
Enter fullscreen mode Exit fullscreen mode

Let’s compare it with the old way of accessing array elements in JavaScript:

console.log(fruits[fruits.length - 1]); // "cherry"
Enter fullscreen mode Exit fullscreen mode

With at(), my code looks intentional, not desperate.

Why use Array.prototype.at()?

Let’s have a look at some points that makes using this method fun:

  • Effortless negative indexing: It allows me to grab the last element with -1, no math needed.
  • Cleaner syntax: It’s straightforward, making my code easier to follow.
  • Works beyond arrays: Strings, typed arrays, it handles them all.
const greeting = "Hello";
console.log(greeting.at(-1)); // "o"
const int8 = new Int8Array([1, 2, 3]);
console.log(int8.at(-1)); // 3
Enter fullscreen mode Exit fullscreen mode

Edge cases to keep in mind

There are some edge cases that I got to know while using the at() method:

  • Out of bound indexes: This is the first thing I learnt that at() handles out of bound indexes gracefully. Out-of-bounds indexes return undefined.
  • Fractional indexes: This is one of the coolest part here. Fractional indexes are truncated. The method truncates decimals to integers, ensuring predictable behavior.
const nums = [10, 20];
console.log(nums.at(5)); // undefined
console.log(nums.at(-5)); // undefined
console.log(nums.at(1.5)); // 20 (1.5 is truncated to 1, not rounded)
console.log(nums.at(2.5)); // undefined (2.5 becomes 2, which is out of bounds)
Enter fullscreen mode Exit fullscreen mode

Browser support

Array.prototype.at() is supported in all modern browsers (Chrome 92+, Firefox 90+, Safari 15.4+).

For older browser versions I found below polyfill working perfectly:

if (!Array.prototype.at) {
  Array.prototype.at = function (n) {
    if (this == null) throw new TypeError("Called on null or undefined");
    const len = this.length >>> 0;
    n = Number(n);
    if (isNaN(n)) n = 0;
    n = n < 0 ? Math.ceil(n) : Math.floor(n); // manual truncation
    if (n < 0) n += len;
    if (n < 0 || n >= len) return undefined;
    return this[n];
  };
}
Enter fullscreen mode Exit fullscreen mode

Some real world use cases

I have found some real world cases where this can be useful:

Accessing the last element

const messages = ["Hi", "How are you?", "See you soon"];
const latest = messages.at(-1); // "See you soon"
Enter fullscreen mode Exit fullscreen mode

String manipulation

const text = "coding";
const lastChar = text.at(-1); // 'g'
Enter fullscreen mode Exit fullscreen mode

Peeking at the top of a stack

const historyStack = ["/home", "/about", "/contact"];
const current = historyStack.at(-1); // "/contact"
Enter fullscreen mode Exit fullscreen mode

Final takeaway

Today we looked at another simple but cool JavaScript method which can make your array handling beautiful.

Adopt this array method in your project and share with me your thoughts in the comment.

Thank you. Let’s meet again with another cool JavaScript trick.

Thank you for being a part of the community

Top comments (0)