Array.prototype.at

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.


This content originally appeared on David Walsh Blog and was authored by David Walsh

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.


This content originally appeared on David Walsh Blog and was authored by David Walsh


Print Share Comment Cite Upload Translate Updates
APA

David Walsh | Sciencx (2021-11-08T01:50:20+00:00) Array.prototype.at. Retrieved from https://www.scien.cx/2021/11/08/array-prototype-at/

MLA
" » Array.prototype.at." David Walsh | Sciencx - Monday November 8, 2021, https://www.scien.cx/2021/11/08/array-prototype-at/
HARVARD
David Walsh | Sciencx Monday November 8, 2021 » Array.prototype.at., viewed ,<https://www.scien.cx/2021/11/08/array-prototype-at/>
VANCOUVER
David Walsh | Sciencx - » Array.prototype.at. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/08/array-prototype-at/
CHICAGO
" » Array.prototype.at." David Walsh | Sciencx - Accessed . https://www.scien.cx/2021/11/08/array-prototype-at/
IEEE
" » Array.prototype.at." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2021/11/08/array-prototype-at/. [Accessed: ]
rf:citation
» Array.prototype.at | David Walsh | Sciencx | https://www.scien.cx/2021/11/08/array-prototype-at/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.