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:

Implementing Infinite Scroll In Next Js With Server Actions

Implementing infinite scroll in Next.js with Server Actions

Infinite scrolling in Next.js no longer requires external libraries — Server Actions let us fetch initial data directly on the server.

Rahul Chhodde
Apr 19, 2024 ⋅ 10 min read
Integrating Django Templates With React For Dynamic Webpages

Integrating Django templates with React for dynamic webpages

Create a dynamic demo blog site using Django and React to demonstrate Django’s server-side functionalities and React’s interactive UI.

Kayode Adeniyi
Apr 18, 2024 ⋅ 7 min read
Using Aoi Js To Build A Bot For Discord

Using aoi.js to build a bot on Discord

Explore how the aoi.js library makes it easy to create Discord bots with useful functionalities for frontend applications.

Rahul Padalkar
Apr 17, 2024 ⋅ 9 min read
Web Components Adoption Guide: Overview, Examples, And Alternatives

Web Components adoption guide: Overview, examples, and alternatives

Evaluate Web Components, a set of standards that allow you to create custom HTML tags for more reusable, manageable code.

Elijah Asaolu
Apr 16, 2024 ⋅ 11 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