FrontendDeveloper.in

ECMAScript question detail

Array .at() method

The .at() method is used to access an array or string elements by passing the negative index value. i.e, It allows accessing values from the end of an array or from a string.

Before ES2022, You should have to access the elements from the end as below,

const array = [1, 2, 3, 4, 5];
console.log(array[array.length - 2]); //4
console.log(array.slice(-2)[0]); //4

const string = '12345';
console.log(string[string.length - 2]); // '4'
console.log(string.slice(-2)[0]); // '4'

Now you should be able to write:

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

const string = '12345';
console.log(string.at(-2));
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399