JavaScript at() method

JavaScript at() method

2023-06-16
1 min read

introduction

The at() method in Array takes an int value as a parameter and returns the element of the given position(index) in the araay. If there is no data by int value, it returns undefined.

Examples

js
const foo = ["a", "b", "c" , "d", "e"]
console.log(foo.at(0)) // "a"
console.log(foo.at(-1)) // "e"
console.log(foo.at(7)) // undefined
console.log(foo.at()) // "a"

The at() method plays same role as bracket notation [] in Array (array[int]). Moreover, The at() method can have not only positive but also negative integer value. It's same as array[array.length - integer value]. The at() method can be passed empty. In this case, it will return first element. Shortly, it means default is 0)

Differences

You may get a questions why at() method is developed if it's same as [] in array. The big difference between at() method and [] is you cannot assign element by index.

js
const fruits = ['apple', 'banana', 'orange']
fruits.at(0) = 'pineapple' // No!
fruits[0] = 'pineapple'

The at() method will cause Invalid assignment target error.

The other difference is that the at() method can have negative integer to get element from end of list.

js
const fruits = ['apple', 'banana', 'orange']
console.log(fruits.at(-1)) // "orange"
console.log(fruits[-1]) // "undefined"

If you use negative integer in [], you will get undefined.

Ref

Free open source project made by Youngjin