Categories
Featured Development Resources HTML/Javascript

JavaScript Array Negative Index Access With the New at() Method

Negative array indexing is a nice feature to have as it allows you to easily access items at the end of an array. 

Python Negative Index Access

If you’ve used Python you are likely familiar with the way that you can access the last element in an Python list like this example:

list = [1,2,3,4,5]
print(list[-1])
# 5

Accessing End Elements Of An Array In Older JavaScript

In older iterations of JavaScript you needed to get the length of the array and subtract that from the desired distance from the end of the array.

arr = [1,2,3,4,5]
console.log(arr[arr.length - 1])
// 5

You could also write a complicated Polyfill if you really wanted to have this syntax, but that fortunately that is now very unnecessary.

Accessing Array End Elements With Slice

With ES6 JavaScript added in the slice method that allowed you to get an array like this, but since slice returns an array you needed to add a [0] to access the returned element.

arr = [1,2,3,4,5]
console.log(arr.slice(-1)[0])
// 5

Introducing The Amazing Javascript Array at() Method

A recent addition to JavaScript, available now in all major browsers is the very handy Array.Prototype.at() method.

With the array at() method you can use negative identifiers for easy access to elements at the end of an array just like with Python just like this code snippet:

arr = [1,2,3,4,5]
console.log(arr.at(-1))
// 5

Easier Access To Random Array Elements

Another nice behavior of the at() is that it will automatically access the floor of whichever number is sent to the at function, which means you can do something like:

arr = [1,2,3,4,5]
console.log(arr.at(Math.random(arr.length)))
// returns a random element from the array

Doing this with the normal accessing syntax returns undefined:

arr = [1,2,3,4,5]
console.log(arr[Math.random(arr.length)])
// returns undefined

Conclusion

Definitely a great method and a welcome addition in JavaScript, bringing a feature that Python developers have always loved.