What is .at()? And why you should use it? 
- javascript

What is .at()? And why you should use it? - javascript

The at() method

Using the at() method, you can retrieve any item at a given index. Both positive and negative integers are valid. Negative integers count backwards from the last item in the array. It allows developers to seamlessly grab elements based on their indexes.

The method .at() is supported by indexable values like Array, String, or TypedArray. it was introduced with ECMAScript 2022.

Syntax

at(index)

Paramaters

index

Zero-based index of the array element to be returned, converted to an integer. A negative index counts backwards from the end of the array — if index < 0, index + array.length is accessed. The index parameter defaults to 0.

Return value

The element in the array that matches the given index. Always returns undefined if index < -array.length or index >= array.length without attempting to access the corresponding property.

Why you should use it

The at() method vs the bracket notation

The at() method is equivalent to the bracket notation when index is non-negative. However, when counting elements from the end of the array, you cannot use array[-1] as you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading array["-1"], which is just a normal string property instead of an array index.

The at() method vs the length property

The usual practice is to access length and calculate the index from that — for example, array[array.length - 1]. The at() method allows relative indexing, so this can be shortened to array.at(-1).

// Our array with items
const colors = ['red', 'green', 'blue'];

// Using length property
const lengthWay = colors[colors.length-2];
console.log(lengthWay); 
// output: 'green'

// Using at() method
const atWay = colors.at(-2);
console.log(atWay); 
// output: 'green'

The at() method vs the slice method

The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.

// Our array with items
const colors = ['red', 'green', 'blue'];

// Using slice() method. Note an array is returned

const sliceWay = colors.slice(-2, -1);
console.log(sliceWay[0]);
// output: 'green'

// Using at() method
const atWay = colors.at(-2);
console.log(atWay); 
// output: 'green'

The at() method is generic. It only expects the this value to have a length property and integer-keyed properties.

The .at() method accepts numbers with a decimal

When a number with a decimal passes to the .at() method, it considers the value before the decimal point and returns the item at that index.

const arr = [1, 2, "three", 4, 5, true, false];
console.log(arr.at(0.6)); 
//  Output: 1

console.log(arr.at(-3.6)); 
//Output: 5

In the code above, the first console outputs the item at the 0 index while the second console counts three from the end of the array and outputs the found item.

The .at() method saves us the extra steps of using Math.floor to floor a random number.

Using the square bracket notation is not possible unless we first floor the random number (that is, round the number down to the nearest integer), as seen in the code below:

const randomIndex = Math.floor(Math.random() * computerOptions.length);

console.log(computerOptions[randomIndex]);

This is because the bracket notation returns an undefined value for numbers with decimals:

const arr = [1, 2, "three", 4, 5, true, false];
console.log(arr[0.6]); 
//Output: undefined

Examples

Negative index

const array = [88, 2, "hey", 2130, true];

let index = 3;

console.log("With an index of ${- index}, ${array.at(-index)} is returned');

//output: With an index of -3, hey is returned

Default

const title = "JavaScript";

title.at(); 
// index defaults to 0 -> "J"
title.at(0); 
// reads first character -> "J"
title.at(1); 
// reads second character -> "a"

Out of bound

const action = "Go";

title.at(0); 
// "G"
title.at(1); 
// "o"
title.at(2); 
// undefined
title.at(10); 
// undefined

Decimal number

const name = "Habiba";

name.at(1); // "a"
name.at(1.1); // "a"
name.at(1.5); // "a"
name.at(1.99999); // "a"

As you can see, the index is converted to a number. It is not rounded. Instead, all the values after the decimal point are ignored.

Browser compatibility

Browser compatibility

Conclusion

The .at() method saves us the extra steps of using Math.floor to floor a random number, which is easy when grabbing items based on their index. It is also concise to use compared to the preexisting methods.

Generally, the major takeaway is that it saves us the extra steps of using Math.floor to floor a random number, is easy when grabbing items based on their index. It is also concise to use compared to the preexisting methods.

Thank you for your time, I hope you found it useful. ❤️