Monday, 8 November, 2021 UTC


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"];; // "three"; // "two"; // "zero"
at is a very little known function but useful, if only for the shorthand syntax!
The post appeared first on David Walsh Blog.