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:

Nx Adoption Guide: Overview, Examples, And Alternatives

Nx adoption guide: Overview, examples, and alternatives

Let’s explore Nx features, use cases, alternatives, and more to help you assess whether it’s the right tool for your needs.

Andrew Evans
Mar 28, 2024 ⋅ 9 min read
Understanding Security In React Native Applications

Understanding security in React Native applications

Explore the various security threats facing React Native mobile applications and how to mitigate them.

Wisdom Ekpotu
Mar 27, 2024 ⋅ 10 min read
Warp Adoption Guide: Overview, Examples, And Alternatives

warp adoption guide: Overview, examples, and alternatives

The warp web framework for Rust offers many enticing features. Let’s see when and why you should consider using warp in your projects.

Ukeje Goodness
Mar 26, 2024 ⋅ 8 min read
Integrating Next Js And Signalr For Enhanced Real Time Web App Capabilities

Integrating Next.js and SignalR to build real-time web apps

In this tutorial, you’ll learn how to integrate Next.js and SignalR to build an enhanced real-time web application.

Clara Ekekenta
Mar 25, 2024 ⋅ 8 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