loading...

item() on built-in indexables

hemanth profile image hemanth.hm Updated on ・2 min read

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.item(0); // 1

nums.item(-1); // 3

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

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

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

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

unit8.item(-1); // 3

unit8.item(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:

Discussion

pic
Editor guide
Collapse
gokulkrishh profile image
Gokulakrishnan Kalaikovan

Hmm, interesting but I think the item property name to get the value is kind of misleading.

.get make sense here ?🙄🧐

Collapse
hemanth profile image
hemanth.hm Author

In accordance to NodeList#item it makes sense?

Collapse
gokulkrishh profile image
Gokulakrishnan Kalaikovan

Yes, if you put it that way. But indexables are not DOM nodes right?