Using the new array.at() method

There is a new array method on the block. It's array.at() and the main difference vs the normal square brackets access syntax is the support for the negative indexes.

Let's consider the following array:

const legumes = [
    "beans", 
    "peanuts", 
    "clover",
    "lentils"
]

At a first glace [] and at() will do the same thing:

legumes[0] // "beans"
legumes.at(0) // "beans"

But while legumes[-1] will end up in returning undefined the legumes.at(-1) will return "lentils".

legumes[-1] // undefined
legumes.at(-1) // "lentils"

With the classic square brackets syntax, we will need to use a trick like the following to access the last element in the array:

legumes[legumes.length - 1] // lentils

The negative indexes in the at() method will give us a more natural way to access elements at the end of the array:

legumes.at(-2) // "clover"
legumes.at(-3) // "peanuts"

Keep in mind that for the moment Safari does not yet support negative indexes.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X