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.
Unlike the traditional bracket notation (e.g.,
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.
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.
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.
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
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉