Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.at

Returns the element at an index; negative indexes are allowed.

Available since: ES2022

Syntax

array.at(index)

Parameters

ParameterTypeDescription
indexnumberThe position of the element, counting from zero. A negative number counts from the end.

Return value

anyThe element, or undefined if there is no such position.

Examples

The last element:

const colors = ['red', 'green', 'blue'];
 
console.log(colors.at(-1));

Output:

blue

Positive indexes work like square brackets:

const colors = ['red', 'green', 'blue'];
 
console.log(colors.at(0), colors[0]);
console.log(colors.at(-2));
console.log(colors.at(10));

Output:

red red
green
undefined

Notes

colors[-1] does not work as in Python — it reads a property named -1 and gives undefined. To count from the end you need at().

See also

Related recipes

In the tutorial

  • Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.

Thanks for reading!

Donate to the site — we work hard for you.