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:

Exploring Hurl An Alternative To Postman

Exploring Hurl, a command line alternative to Postman

Hurl is an excellent Postman alternative that improves the DX of working with APIs through the command line.

Nwani Victory
May 20, 2024 ⋅ 8 min read
How To Integrate WunderGraph With Your Frontend Application

How to integrate WunderGraph with your frontend application

Unify and simplify APIs using WunderGraph to integrate REST, GraphQL, and databases in a single endpoint.

Boemo Mmopelwa
May 17, 2024 ⋅ 5 min read
Understanding The Latest Webkit Features In Safari 17.4

Understanding the latest Webkit features in Safari 17.4

The Safari 17.4 update brought in many modern features and bug fixes. Explore the major development-specific updates you should be aware of.

Rahul Chhodde
May 16, 2024 ⋅ 10 min read
Using Webrtc To Implement Peer To Peer Video Streaming In A Node Js Project

Using WebRTC to implement P2P video streaming

Explore one of WebRTC’s major use cases in this step-by-step tutorial: live peer-to-peer audio and video streaming between systems.

Oduah Chigozie
May 16, 2024 ⋅ 18 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