JavaScript Array at() Method

The JavaScript Array.at() is a newer feature (ES2022) that makes accessing elements in an array easier, especially when dealing with negative indices.

This article will explore the at() method, how it works, and some practical use cases.

JS Arrat.at()

The JavaScript Array at() Method

Unlike the traditional bracket notation (e.g., array[index]), the at() method accepts both positive and negative indices.

When we give it a positive index, the at() method behaves similarly to the bracket notation.

But, when given a negative index, it counts from the end of the array, making it simpler to access elements near the end of an array.

Syntax:

someArray.at(index)

The index can be a positive or negative integer (and floating point, interestingly 🤔).

This returns an element at the specified index or undefined if the index is out of range.

Examples

const pizzaTypes = [
  'Margherita',
  'Pepperoni',
  'BBQ Chicken',
  'Hawaiian',
  'Veggie Supreme',
];

console.log(pizzaTypes.at(0)); // 👉 'Margherita'
console.log(pizzaTypes.at(-1)); // 👉 'Veggie Supreme'
console.log(pizzaTypes.at(10)); // 👉 undefined

Something interesting that I learned from a video by Wes Bos is that you can also use floating point numbers, and it will behave as if that value has had the Math.floor() method applied to it.

The Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number

Let's look at an example:

const pizzaTypes = [
  'Margherita',
  'Pepperoni',
  'BBQ Chicken',
  'Hawaiian',
  'Veggie Supreme',
];

console.log(pizzaTypes.at(1.9234)); // Behaves like 1 👉 'Pepperoni'
console.log(pizzaTypes.at(-1.6)); // Behaves like -1 👉 'Veggie Supreme'
console.log(pizzaTypes.at(10.1)); // Behaves like 10 👉 undefined

A use case for this behavior might be selecting a random item from the array:

const pizzaTypes = [
  'Margherita',
  'Pepperoni',
  'BBQ Chicken',
  'Hawaiian',
  'Veggie Supreme',
];

// No need to floor the value to satisfy the index like the traditional brackets notation.
const randomPizza = pizzaTypes.at(Math.random() * pizzaTypes.length); 

console.log(randomPizza); // Random pizza each time you log 

Hopefully, this short article gave you ideas on when and how to use the Array.at() method.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

JSJavaScriptEs2020
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.