This is the part that I don't get, though. If arr[-1] returns undefined, then that means one of two things:
Existing code checks to make sure indices are never negative.
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.)
Software dev at Netflix | DC techie | Conference speaker | egghead Instructor | TC39 Educators Committee | Girls Who Code Facilitator | Board game geek | @laurieontech on twitter
"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."
This is the part that I don't get, though. If
arr[-1]
returnsundefined
, then that means one of two things:arr[index]
is truthy (or explicitly checks if it'sundefined
).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 returnundefined
(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.)
"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-...
Oh, gotcha! So it would break existing code. Thanks for the reference!