Codementor Events

Array.prototype.at() - An intuitive way to retrieve elements

Published Jul 16, 2022
Array.prototype.at() - An intuitive way to retrieve elements

The array.prototype.at() method accepts an integer and returns the value at that index.

Usage

const colors = ["red", "blue", "green", "yellow"];

console.log(colors.at(1)); // blue

If no value is found at the specified index, this method returns undefined.

You might be wondering how is it different from using the [] bracket notation?

The at() method accepts negative values as well. When a negative value is provided the array is traversed from behind, thus returning a value from the end of the array.

See the example below to understand better:

const colors = ["red", "blue", "green", "yellow"];

// get the last item
console.log(colors.at(-1)); // yellow

// get the 2nd last item
console.log(colors.at(-2)); // green

// get the 3rd last item
console.log(colors.at(-3)); // blue

Now lets try the same example with [] bracket:

const colors = ["red", "blue", "green", "yellow"];

// get the last item
console.log(colors[colors.length - 1]); // yellow

// get the 2nd last item
console.log(colors[colors.length - 2]); // green

// get the 3rd last item
console.log(colors[colors.length - 3]); // blue

The at() method works with strings as well:

const text = "you got an at-titude";

// get the last letter from text

console.log(text.at(-1)); // e

Browser Support

Array.prototype.at() is supported in the recent versions of most browsers. Find out more at https://caniuse.com/mdn-javascript_builtins_array_at

Conclusion

While there isn’t anything wrong in using the [] bracket notation, it’s much more intuitive to use the at() method especially when you want to retrieve a value from the end of an array.

Discover and read more posts from Gaurav Sen
get started