index with JavaScript

calculating....


  1. JavaScript

Today, we’re going to look at the Array.prototype.at() method: what it does, how it works, and why you might want to use it over simple bracket notation.

Getting an array item by index

The Array.prototype.at() method gets an array item at a specific index. Pass the index in as an argument.

Let’s imagine you have an array of wizards

let wizards = ['Merlin', 'Ursula', 'Ragadast', 'Gandalf'];

You can use the Array.prototype.at() method to get the item at index 2 like this…

// returns "Ragadast"
let radagast = wizards.at(2);

Why would you use this over bracket notation?

JavaScript already provides a way to get items by their index: bracket notation.

// returns "Ursula"
let ursula = wizards[1];

So… why would you use the Array.prototype.at() method instead of bracket notation?

The Array.prototype.at() method has one advantage over bracket notation: it supports negative indexes.

// returns undefined
let maybeGandalf = wizards[-1];

If you used an index of -1 with bracket notation, you get undefined as the returned value.

let gandalf = wizards.at(-1);

But with the Array.prototype.at() method, negative indexes are counted backwards from the end of the array. An index of -1 returns Gandalf instead.

🐘 When you need index with modern JavaScript.

If you enjoyed this article, you may also like Dervic Blog's.


Comments (0)

Thank you!