DEV Community

hemanth.hm
hemanth.hm

Posted on • Edited on

2 1

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?

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️