DEV Community

Discussion on: `at` coming soon to ECMAScript

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Huh, TIL! I wonder why they wouldn't just extend the indexing operator to support negative indices. Seems easier than introducing a method, and now there's the question of which to use.

Collapse
 
laurieontech profile image
Laurie

Because it is already a valid index and would break existing code.

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan • Edited

This is the part that I don't get, though. If arr[-1] returns undefined, then that means one of two things:

  1. Existing code checks to make sure indices are never negative.
  2. Existing code checks if arr[index] is truthy (or explicitly checks if it's undefined).

Either way, I don't see it breaking existing code if arr[-1] all of a sudden starts returning the last entry of an array. If we're doing #1, the API doesn't change for us since our code explicitly prohibits negative indexing. If we're doing #2, it still doesn't change because now negative indexing doesn't return undefined (unless the last element is, literally, undefined).

I only see this being an issue for actual objects. Can't arrays override the behavior of the indexing operator? (I'm not familiar with those kinds of low-level implementation details for JavaScript, so maybe not.)

 
laurieontech profile image
Laurie

"Unfortunately, JS's language design makes this impossible. The [] syntax is not specific to Arrays and Strings; it applies to all objects. Referring to a value by index, like arr[1], actually just refers to the property of the object with the key "1", which is something that any object can have. So arr[-1] already "works" in today's code, but it returns the value of the "-1" property of the object, rather than returning an index counting back from the end."

github.com/tc39/proposal-relative-...

 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Oh, gotcha! So it would break existing code. Thanks for the reference!

Collapse
 
stegriff profile image
Ste Griffiths

The article covers this really:

Well, as it turns out, -1 is already a valid key. Arrays are really objects with indices as keys. So arr[-1] is looking at the arr object and the value of the "-1" key, which is undefined.

There can be a "-1" key present in the object, so the behaviour for "negative indices" is already defined by the language.