Array.prototype.at

By  on  

Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript has added methods like find and `findIndex recently, but one syntax I love from languages like Python is retrieving values by negative indexes.

When you want to get the value of the last item in an array, you end up with an archaic expression:

const arr = ["zero", "one", "two", "three"];
const last = arr[arr.length - 1];

You could use pop but that modifies the array. Instead you can use at and an index, even a negative index, to retrieve values:

const arr = ["zero", "one", "two", "three"];
arr.at(-1); // "three"
arr.at(-2); // "two"
arr.at(0); // "zero"

at is a very little known function but useful, if only for the shorthand syntax!

Recent Features

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Incredible Demos

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!