DEV Community

hemanth.hm
hemanth.hm

Posted on • Updated on

at() on built-in indexables

You might have tried to access the last element in array using arr[arr.length-1] and wondered if we had support for [-indx] negative-index but the same wouldn't apply for String and TypedArrays as -indx would be a property on them rather than the index.

Hence we have item() a proposal on stage-3 is a method on the prototype of the built-in indexable objects: Array, String, and TypedArrays objects, it also supports relative indexing from the end when passed a negative index.

Let us look into few examples:

let nums = [1,2,3];

nums.at(0); // 1

nums.at(-1); // 3

nums.at(100); // undefined
Enter fullscreen mode Exit fullscreen mode
let name = 'ECMA';

name.at(0); // "E"

name.at(-1); // "A"

name.at(100); // undefined
Enter fullscreen mode Exit fullscreen mode
let unit8 = new Uint8Array([1,2,3]);
unit8.at(0); // 1

unit8.at(-1); // 3

unit8.at(100); // undefined
Enter fullscreen mode Exit fullscreen mode

indx will be converted to 0 for NaN, null, +0, -0 or undefined

If this proposal gets adopted, the following legacy interfaces should be upgradable into ObservableArray:

Update:


It's worth noting that YUI 2/3 duck-typing on item() means that we'll need a different name for web compat reasons. @_shu suggested at()

— Alex Russell (@slightlylate) November 12, 2020

Top comments (1)

Collapse
 
hemanth profile image
hemanth.hm

In accordance to NodeList#item it makes sense?