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:

Hand holding purple sticky notes for CSS sticky positioning guide.

Troubleshooting CSS sticky positioning

Fix sticky positioning issues in CSS, from missing offsets to overflow conflicts in flex, grid, and container height constraints.

Ibadehin Mojeed
Nov 13, 2024 ⋅ 5 min read
Task Scheduling and cron Jobs in Node Using node-cron

Scheduling tasks in Node.js using node-cron

From basic syntax and advanced techniques to practical applications and error handling, here’s how to use node-cron.

Godwin Ekuma
Nov 12, 2024 ⋅ 7 min read
Working With The Angular Tree: Flat Vs Nested Trees And More

Working with the Angular tree

The Angular tree view can be hard to get right, but once you understand it, it can be quite a powerful visual representation.

Lewis Cianci
Nov 12, 2024 ⋅ 21 min read

Why you should use SWC (and not Babel)

In this post, we’ll compare Babel and SWC based on setup, execution, and speed.

Kasra Khosravi
Nov 12, 2024 ⋅ 9 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