Array.prototype.at
Publikováno: 8.11.2021
Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript has added methods like find and `findIndex recently, but one syntax I love from languages like Python is retrieving values by negative indexes. When you want to get the value of the […]
The post Array.prototype.at appeared first on David Walsh Blog.
Working with arrays is an essential skill in any programming language, especially JavaScript, as we continue to rely on external data APIs. JavaScript has added methods like find
and `findIndex
recently, but one syntax I love from languages like Python is retrieving values by negative indexes.
When you want to get the value of the last item in an array, you end up with an archaic expression:
const arr = ["zero", "one", "two", "three"]; const last = arr[arr.length - 1];
You could use pop
but that modifies the array. Instead you can use at
and an index, even a negative index, to retrieve values:
const arr = ["zero", "one", "two", "three"]; arr.at(-1); // "three" arr.at(-2); // "two" arr.at(0); // "zero"
at
is a very little known function but useful, if only for the shorthand syntax!
The post Array.prototype.at appeared first on David Walsh Blog.