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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
hemanth profile image
hemanth.hm

In accordance to NodeList#item it makes sense?

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay