2021-10-15
1630
#vanilla javascript
Ibadehin Mojeed
72024
Oct 15, 2021 ⋅ 5 min read

Using JavaScript’s .at() method

Ibadehin Mojeed I'm an advocate of project-based learning. I also write technical content around web development.

Recent posts:

Rxjs Adoption Guide: Overview, Examples, And Alternatives

RxJS adoption guide: Overview, examples, and alternatives

Get to know RxJS features, benefits, and more to help you understand what it is, how it works, and why you should use it.

Emmanuel Odioko
Jul 26, 2024 ⋅ 13 min read
Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 ⋅ 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 ⋅ 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 ⋅ 5 min read
View all posts

6 Replies to "Using JavaScript’s <code>.at()</code> method"

  1. .at() is really useful but would be better to just add support into index operator. I know that there is possibility of having “-1” key/index, but what could have been done is if the key exist then return the value of the key else return value from length minus the supplied negative value. There is very rare possibility that “-1” is used as a key by anyone till date.

    1. I hope you understand its just not “-1” and can be “-2”, “-3”, …., “-100000000”,… you got me I think!

  2. I think your random number example has an issue. Math.random() returns between 0 and 1 inclusive which could put the index beyond the length of the array and result in an undefined.

    1. Hi James, thanks for reading. Be aware that Math.random() returns value between 0 (inclusive) and 1 (exclusive). Meaning it never returns 1. So by multiplying that with the array length of 3, we will never get a value of 3. So the output is 0, 1 and 2. And that will never result in an undefined. Thank you.

  3. Brilliant article thank you. I particularly liked your examples, and I had no idea you could store a value at the index -1!

    What’s really interesting is that if you set an array with a value at -1 such:

    “`
    let arr = [0, 1, 2];
    arr[-1] = -1
    “`

    And then use at:

    “`
    arr.at(-1) // returns 2
    “`

    It returns 2 rather than the value you set.

    Also, the fact that you can use decimal values with `at` is a gamechanger!

Leave a Reply