A new array method, array.at
, is in stage three of the TC39 process.
When a new feature is included in JavaScript, it has to pass through the TC39 process. This process has five stages.
Stage 0: Strawperson - idea for the addition of a new feature or change in existing features.
Stage 1: Proposal — explains the exact problem and how it can be solved.
Stage 2: Draft — the syntax, semantics are provided and it should be runnable in a browser or through a transpiler like Babel.
Stage 3: Candidate — further refinements are decided based on feedback from implementations and users.
Stage 4: Finished — the feature is ready for inclusion in the formal ECMAScript.
The proposal for the
at
method in array object can be found here.
The at
method takes an integer(index_position
) as an argument and returns the item at that index of the array.
array.at(index);
let numbers = [1,2,3,4,5];
numbers.at(0); // 1
We are allowed to pass both positive and negative numbers. The negative index counts from the last item of the array.
let numbers = [1,2,3,4,5];
numbers.at(-1); // 5
numbers.at(-3); // 3
When we try to access an index that is not present in the array, undefined
will be returned.
let numbers = [1,2,3,4,5];
numbers.at(100); // undefined
at
method different from the square bracket syntax?Square brackets are commonly used to access the elements of an array using an index. However, if we needed to get the last element of the array, we would do the following:
let num = [1,2,3,4,5];
let lastNum = num[num.length - 1] ;
But, with the at
method, we can access the last element of the array by passing a negative index.
let num = [1,2,3,4,5];
let lastNum = num.at(- 1);
You can get the polyfill for the
at
method from here.